text
stringlengths
1.02k
43.5k
conversation_id
int64
853
107k
embedding
list
cluster
int64
24
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is an introvert person. In fact he is so much of an introvert that he plays "Monsters and Potions" board game alone. The board of the game is a row of n cells. The cells are numbered from 1 to n from left to right. There are three types of cells: a cell containing a single monster, a cell containing a single potion or a blank cell (it contains neither a monster nor a potion). Polycarp has m tokens representing heroes fighting monsters, which are initially located in the blank cells s_1, s_2, ..., s_m. Polycarp's task is to choose a single cell (rally point) and one by one move all the heroes into this cell. A rally point can be a cell of any of three types. After Policarp selects a rally point, he picks a hero and orders him to move directly to the point. Once that hero reaches the point, Polycarp picks another hero and orders him also to go to the point. And so forth, until all the heroes reach the rally point cell. While going to the point, a hero can not deviate from the direct route or take a step back. A hero just moves cell by cell in the direction of the point until he reaches it. It is possible that multiple heroes are simultaneously in the same cell. Initially the i-th hero has h_i hit points (HP). Monsters also have HP, different monsters might have different HP. And potions also have HP, different potions might have different HP. If a hero steps into a cell which is blank (i.e. doesn't contain a monster/potion), hero's HP does not change. If a hero steps into a cell containing a monster, then the hero and the monster fight. If monster's HP is strictly higher than hero's HP, then the monster wins and Polycarp loses the whole game. If hero's HP is greater or equal to monster's HP, then the hero wins and monster's HP is subtracted from hero's HP. I.e. the hero survives if his HP drops to zero, but dies (and Polycarp looses) if his HP becomes negative due to a fight. If a hero wins a fight with a monster, then the monster disappears, and the cell becomes blank. If a hero steps into a cell containing a potion, then the hero drinks the potion immediately. As a result, potion's HP is added to hero's HP, the potion disappears, and the cell becomes blank. Obviously, Polycarp wants to win the game. It means that he must choose such rally point and the order in which heroes move, that every hero reaches the rally point and survives. I.e. Polycarp loses if a hero reaches rally point but is killed by a monster at the same time. Polycarp can use any of n cells as a rally point β€” initially it can contain a monster, a potion, or be a blank cell with or without a hero in it. Help Polycarp write a program to choose a rally point and the order in which heroes move. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 100; 1 ≀ m ≀ n) β€” length of the game board and the number of heroes on it. The following m lines describe heroes. Each line contains two integers s_i and h_i (1 ≀ s_i ≀ n; 1 ≀ h_i ≀ 10^6), where s_i is the initial position and h_i is the initial HP of the i-th hero. It is guaranteed that each cell s_i is blank. It is also guaranteed that all s_i are different. The following line contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_j ≀ 10^6), where a_j describes the i-th cell of the game board: * a_j=0 means that the i-th cell is blank, * a_j<0 means that the i-th cell contains monster with positive HP of -a_j, * a_j>0 means that the i-th cell contains potion with a_j HP. Output On the first line of the output print the index of the rally point cell. On the second line print m integers β€” the order in which heroes should move to the rally point. Heroes are numbered from 1 to m in the order they are given in the input. If there are multiple solutions, print any of them. If it is impossible to find a rally point which can be reached by all heroes, print a single integer -1 in the output. Examples Input 8 3 8 2 1 3 4 9 0 3 -5 0 -5 -4 -1 0 Output 6 3 1 2 Input 1 1 1 1 0 Output 1 1 Input 3 2 1 1 3 1 0 -5000 0 Output -1 Input 8 3 1 15 5 10 8 1 0 -5 -5 -5 0 -5 -5 0 Output 7 2 1 3 Note The picture illustrates the first example: <image> Tags: brute force, dp, greedy, implementation Correct Solution: ``` #!/usr/bin/env python3 import collections import sys import traceback class Input(object): def __init__(self): self.fh = sys.stdin def next_line(self): while True: line = sys.stdin.readline() if line == '\n': continue return line def next_line_ints(self): line = self.next_line() return [int(x) for x in line.split()] def next_line_strs(self): line = self.next_line() return line.split() class Hero(object): def __init__(self, id, hp): self.id = id self.hp = hp class Room(object): def __init__(self, value): self.heros = [] self.value = value def get_orders(cells, heros): n = len(cells) rooms = [Room(cell) for cell in cells] for i in range(len(heros)): pos = heros[i][0] - 1 hp = heros[i][1] rooms[pos].heros.append(Hero(i, hp)) for room in rooms: room.heros.sort(key=lambda hero: hero.hp, reverse=True) left_best_heros = [-1] * n left_reach = 0 while left_reach < n and not rooms[left_reach].heros: left_reach += 1 best_hero = None while left_reach < n: if rooms[left_reach].heros: hero = rooms[left_reach].heros[0] if best_hero is None or hero.hp > best_hero.hp: best_hero = hero elif best_hero and best_hero.hp + rooms[left_reach].value >= 0: best_hero.hp += rooms[left_reach].value else: break left_best_heros[left_reach] = best_hero.id left_reach += 1 right_best_heros = [-1] * n right_reach = n - 1 while right_reach > -1 and not rooms[right_reach].heros: right_reach -= 1 best_hero = None while right_reach > -1: if rooms[right_reach].heros: hero = rooms[right_reach].heros[0] if best_hero is None or hero.hp > best_hero.hp: best_hero = hero elif best_hero and best_hero.hp + rooms[right_reach].value >= 0: best_hero.hp += rooms[right_reach].value else: break right_best_heros[right_reach] = best_hero.id right_reach -= 1 #print('left_reach {}, right_reach {}'.format(left_reach, right_reach)) if right_reach + 1 > left_reach: return None, [] rally_point = left_reach - 1 visited = [False for _ in heros] order = [] def put_id(id): if id != -1 and not visited[id]: order.append(id + 1) visited[id] = True for i in range(rally_point, -1, -1): put_id(left_best_heros[i]) for hero in rooms[i].heros: put_id(hero.id) for i in range(rally_point + 1, n): put_id(right_best_heros[i]) for hero in rooms[i].heros: put_id(hero.id) return rally_point + 1, order def main(): input = Input() while True: try: nums = input.next_line_ints() if not nums: break n, m = nums if n == -1: break heros = [] for _ in range(m): heros.append(input.next_line_ints()) cells = input.next_line_ints() except: print('read input failed') try: rally, order = get_orders(cells, heros) if rally is None: print("-1") else: print("{}".format(rally)) print(" ".join([str(x) for x in order])) except: traceback.print_exc(file=sys.stdout) print('get_min_dist failed') main() ```
16,861
[ 0.29443359375, 0.0927734375, 0.1932373046875, 0.2264404296875, -0.267333984375, -0.50634765625, -0.185791015625, 0.25732421875, 0.016357421875, 0.48046875, 1.046875, -0.04803466796875, 0.0948486328125, -0.8583984375, -0.27490234375, 0.298828125, -0.54248046875, -0.64794921875, -0...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Tags: *special, brute force, implementation Correct Solution: ``` n=int(input()) m=[] for i in range(n): x=input() m.append(x) t=0 c=0 for i in range(len(m[0])): t=m[0][i] for j in range(1,len(m)): if m[j][i] != t: c=i print(c) exit() ```
17,931
[ 0.294677734375, -0.07513427734375, 0.2064208984375, 0.455322265625, -0.287109375, -0.433349609375, -0.287109375, -0.276611328125, 0.56689453125, 0.572265625, 0.650390625, 0.07293701171875, 0.295654296875, -0.96044921875, -0.9111328125, 0.04095458984375, -0.488525390625, -0.5546875,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Tags: *special, brute force, implementation Correct Solution: ``` n = int(input()) phones = [] for i in range(n): phones.append(input()) m = len(phones[0]) count = 0 flag = False for j in range(m): compare = phones[0][j] for i in range(n): if compare != phones[i][j]: flag = True if flag: break else: count+=1 print(count) ```
17,932
[ 0.296875, -0.089111328125, 0.191650390625, 0.464111328125, -0.27392578125, -0.437744140625, -0.304931640625, -0.27685546875, 0.58251953125, 0.5791015625, 0.65869140625, 0.07476806640625, 0.31298828125, -0.97119140625, -0.91845703125, 0.04229736328125, -0.4892578125, -0.544921875, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Tags: *special, brute force, implementation Correct Solution: ``` n=int(input()) number=input() for i in range(n-1): li=[] new=input() for j in range(len(number)): if new[j]==number[j]: li.append(number[j]) if new[j]!=number[j]: break number=''.join(li) print(len(number)) ```
17,933
[ 0.268310546875, -0.0823974609375, 0.2056884765625, 0.49951171875, -0.281494140625, -0.410400390625, -0.283447265625, -0.27294921875, 0.55908203125, 0.56787109375, 0.6611328125, 0.067626953125, 0.28369140625, -0.98193359375, -0.94677734375, 0.04534912109375, -0.48095703125, -0.54736...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Tags: *special, brute force, implementation Correct Solution: ``` garbage = int(input()) result = "" all_numbers = [input() for _ in range(garbage)] first_number = all_numbers[0] for i in range(len(all_numbers[0])): ch = True for j in range(garbage): if all_numbers[j][i] != first_number[i]: ch = False break if ch == True: result = result + first_number[i] if ch == False: break print(len(result)) ```
17,934
[ 0.293212890625, -0.065185546875, 0.226806640625, 0.470703125, -0.27392578125, -0.44677734375, -0.276123046875, -0.285888671875, 0.5830078125, 0.56591796875, 0.63525390625, 0.08343505859375, 0.303466796875, -0.9658203125, -0.955078125, 0.042327880859375, -0.47705078125, -0.540039062...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Tags: *special, brute force, implementation Correct Solution: ``` n=int(input()) l=[] for i in range(n): l.append(input()) l1=[] for i in range(len(l)-1): for j in range(len(l[-1])): if l[i][j]!=l[i+1][j]: l1.append(j) print(min(l1)) ```
17,935
[ 0.298095703125, -0.0819091796875, 0.2047119140625, 0.457763671875, -0.27978515625, -0.4169921875, -0.282470703125, -0.27880859375, 0.56591796875, 0.56494140625, 0.64697265625, 0.0745849609375, 0.2939453125, -0.9560546875, -0.91943359375, 0.042083740234375, -0.488037109375, -0.55371...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Tags: *special, brute force, implementation Correct Solution: ``` ''' Design by Dinh Viet Anh(JOKER) //_____________________________________$$$$$__ //___________________________________$$$$$$$$$ //___________________________________$$$___$ //___________________________$$$____$$$$ //_________________________$$$$$$$__$$$$$$$$$$$ //_______________________$$$$$$$$$___$$$$$$$$$$$ //_______________________$$$___$______$$$$$$$$$$ //________________$$$$__$$$$_________________$$$ //_____________$__$$$$__$$$$$$$$$$$_____$____$$$ //__________$$$___$$$$___$$$$$$$$$$$__$$$$__$$$$ //_________$$$$___$$$$$___$$$$$$$$$$__$$$$$$$$$ //____$____$$$_____$$$$__________$$$___$$$$$$$ //__$$$$__$$$$_____$$$$_____$____$$$_____$ //__$$$$__$$$_______$$$$__$$$$$$$$$$ //___$$$$$$$$$______$$$$__$$$$$$$$$ //___$$$$$$$$$$_____$$$$___$$$$$$ //___$$$$$$$$$$$_____$$$ //____$$$$$$$$$$$____$$$$ //____$$$$$__$$$$$___$$$ //____$$$$$___$$$$$$ //____$$$$$____$$$ //_____$$$$ //_____$$$$ //_____$$$$ ''' from math import * from cmath import * from itertools import * from decimal import * # su dung voi so thuc from fractions import * # su dung voi phan so from sys import * from types import new_class #from numpy import * '''getcontext().prec = x # lay x-1 chu so sau giay phay (thuoc decimal) Decimal('12.3') la 12.3 nhung Decimal(12.3) la 12.30000000012 Fraction(a) # tra ra phan so bang a (Fraction('1.23') la 123/100 Fraction(1.23) la so khac (thuoc Fraction) a = complex(c, d) a = c + d(i) (c = a.real, d = a.imag) a.capitalize() bien ki tu dau cua a(string) thanh chu hoa, a.lower() bien a thanh chu thuong, tuong tu voi a.upper() a.swapcase() doi nguoc hoa thuong, a.title() bien chu hoa sau dau cach, a.replace('a', 'b', slg) chr(i) ki tu ma i ord(c) ma ki tu c a.join['a', 'b', 'c'] = 'a'a'b'a'c, a.strip('a') bo dau va cuoi ki tu 'a'(rstrip, lstrip) a.split('a', slg = -1) cat theo ki tu 'a' slg lan(rsplit(), lsplit()), a.count('aa', dau = 0, cuoi= len(a)) dem slg a.startswith('a', dau = 0, cuoi = len(a)) co bat dau bang 'a' ko(tuong tu endswith()) a.index("aa") vi tri dau tien xuat hien (rfind()) input = open(".inp", mode='r') a = input.readline() out = open(".out", mode='w') a.index(val) ''' #inn = open(".inp", "r") n = int(input()) s = [] for x in range(n): s.append(input()) l = 0 r = len(s[0]) def check(x): for _ in range(1, n): if s[_][:x] != s[0][:x]: return 0 return 1 while l < r-1: mid = (l+r)//2 if check(mid): l = mid else: r = mid if check(r): print(r) else: print(l) ```
17,936
[ 0.318115234375, -0.06451416015625, 0.1646728515625, 0.501953125, -0.274169921875, -0.446044921875, -0.279296875, -0.1829833984375, 0.5361328125, 0.60595703125, 0.66455078125, 0.118408203125, 0.328857421875, -0.9560546875, -0.89404296875, 0.049163818359375, -0.393798828125, -0.57714...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Tags: *special, brute force, implementation Correct Solution: ``` n = int(input()) p = input() for x in range(1, n): t = input() if p != t[: len(p)]: j = 0 while p[j] == t[j]: j += 1 p = p[: j] print(len(p)) ```
17,937
[ 0.2861328125, -0.07269287109375, 0.2086181640625, 0.458251953125, -0.283935546875, -0.429443359375, -0.288330078125, -0.268798828125, 0.56396484375, 0.58203125, 0.6513671875, 0.085205078125, 0.294677734375, -0.970703125, -0.9169921875, 0.049346923828125, -0.485595703125, -0.5551757...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Tags: *special, brute force, implementation Correct Solution: ``` n = int(input()) fl = False numbers = [] for i in range(n): numbers.append(input()) first_symbol = '' for j in range(len(numbers[0])): if fl: break first_symbol += numbers[0][j] for i in range(1,n): if numbers[i][0:j+1] != first_symbol: print(len(first_symbol)-1) fl = True break ```
17,938
[ 0.27392578125, -0.093017578125, 0.2154541015625, 0.443359375, -0.26416015625, -0.41796875, -0.24267578125, -0.287353515625, 0.56787109375, 0.5849609375, 0.6396484375, 0.08428955078125, 0.31640625, -0.9638671875, -0.91064453125, 0.059234619140625, -0.47021484375, -0.5517578125, -0...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Submitted Solution: ``` n=int(input()) a=[] for i in range(n): a.append(input()) s='' k=a[0] j=0 r=0 for i in k: for ii in a: if ii[j]==k[j]: pass else: r=1 break else: s=s+k[j] if r==1: break j=j+1 print(len(s)) ``` Yes
17,939
[ 0.35595703125, 0.057647705078125, 0.15283203125, 0.375, -0.428466796875, -0.31787109375, -0.315673828125, -0.1185302734375, 0.468017578125, 0.59326171875, 0.66064453125, 0.0853271484375, 0.2298583984375, -0.9296875, -0.89306640625, 0.05108642578125, -0.485107421875, -0.5947265625, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Submitted Solution: ``` n = int(input()) x = [] for i in range(n): l =input() x.append(l) res = '' prefix = x[0] for string in x[1:]: while string[:len(prefix)] != prefix and prefix: prefix = prefix[:len(prefix) - 1] if not prefix: break res = prefix print(len(str(res))) ``` Yes
17,940
[ 0.349365234375, 0.04705810546875, 0.153564453125, 0.37255859375, -0.414306640625, -0.322509765625, -0.321533203125, -0.12115478515625, 0.484130859375, 0.5927734375, 0.6455078125, 0.0797119140625, 0.2403564453125, -0.9296875, -0.89111328125, 0.053985595703125, -0.4833984375, -0.5844...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Submitted Solution: ``` n = int(input()) max_prefix = input() j = len(max_prefix) for i in range(1, n): s = input() k = 0 while s[k] == max_prefix[k] and k < j: k += 1 j = k print(k) ``` Yes
17,941
[ 0.370361328125, 0.0556640625, 0.1510009765625, 0.408203125, -0.4287109375, -0.315673828125, -0.321533203125, -0.12890625, 0.4658203125, 0.5859375, 0.66015625, 0.09893798828125, 0.2462158203125, -0.9482421875, -0.9013671875, 0.05047607421875, -0.4951171875, -0.58056640625, -0.3964...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Submitted Solution: ``` import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy sys.setrecursionlimit(10**7) inf=10**20 mod=10**9+7 dd=[(-1,0),(0,1),(1,0),(0,-1)] ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] # def LF(): return [float(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def LS(): return sys.stdin.readline().split() def S(): return input() def main(): n=I() l=[S() for _ in range(n)] for i in range(len(l[0])): x=l[0][i] for j in range(n): if l[j][i]!=x: return i return n # main() print(main()) ``` Yes
17,942
[ 0.359619140625, 0.041534423828125, 0.152587890625, 0.412841796875, -0.38525390625, -0.306640625, -0.303466796875, -0.146484375, 0.481689453125, 0.59375, 0.6484375, 0.0799560546875, 0.257568359375, -0.9326171875, -0.88818359375, 0.06768798828125, -0.466552734375, -0.58642578125, -...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Submitted Solution: ``` x=int(input()) l=[] for i in range(x): l=l+[input()] c=l[0] m=1 k=[] for i in range(1,len(l)): while c[:m] in l[i]: m=m+1 k=k+[c[:m-1]] m=1 k.sort() print(len(k[0])) ``` No
17,943
[ 0.3623046875, 0.05010986328125, 0.147705078125, 0.370849609375, -0.416748046875, -0.3134765625, -0.318603515625, -0.11431884765625, 0.47705078125, 0.58251953125, 0.658203125, 0.08447265625, 0.230224609375, -0.93017578125, -0.88720703125, 0.044158935546875, -0.486083984375, -0.58789...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Submitted Solution: ``` n = int(input()) s = [] e = [] f = "" for x in range(n): s.append(input()) for x in range(1,len(s[0])): for y in s[1:]: if s[0][:x] in y: e.append(s[0][:x]) e.reverse() for x in e: if e.count(x) == n - 1: f = str(x) break print(len(f)) ``` No
17,944
[ 0.3544921875, 0.0531005859375, 0.145751953125, 0.39892578125, -0.41943359375, -0.30908203125, -0.317626953125, -0.11407470703125, 0.4794921875, 0.576171875, 0.6650390625, 0.08612060546875, 0.2454833984375, -0.94189453125, -0.90087890625, 0.02850341796875, -0.48046875, -0.58984375, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Submitted Solution: ``` lst=[] for i in range(int(input())): lst.append(input()) ans=0 for j in range(len(lst[0])): for k in range(j+1,len(lst[0])+1): c=0 for l in lst: if lst[0][j:k] in l and lst[0][j:k][0]==lst[0][0]: c+=1 if c==len(lst) and len(lst[0][j:k])>ans: ans=len(lst[0][j:k]) print(ans) ``` No
17,945
[ 0.371337890625, 0.0421142578125, 0.173828125, 0.361328125, -0.4189453125, -0.306396484375, -0.31787109375, -0.11077880859375, 0.477783203125, 0.5849609375, 0.63134765625, 0.06634521484375, 0.2293701171875, -0.908203125, -0.9013671875, 0.037017822265625, -0.49609375, -0.56103515625,...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. Input The first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different. Output Print the number of digits in the city phone code. Examples Input 4 00209 00219 00999 00909 Output 2 Input 2 1 2 Output 0 Input 3 77012345678999999999 77012345678901234567 77012345678998765432 Output 12 Note A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209". In the first sample the city phone code is string "00". In the second sample the city phone code is an empty string. In the third sample the city phone code is string "770123456789". Submitted Solution: ``` num = int(input()) arr, arr2 = ([], []) i = 0 nums = input() for x in range(num - 1): nums = input() while len(arr) < len(nums): arr.append(set()) for y in range(len(nums)): arr[y].add(nums[y]) y = 0 for z in range(len(arr)): if len(arr[z]) == 1 and i == z: arr2.append(arr[z]) i += 1 if len(nums) > 1: print(len(arr2)) else: print(0) ``` No
17,946
[ 0.37646484375, 0.05316162109375, 0.13330078125, 0.376220703125, -0.4169921875, -0.319580078125, -0.311279296875, -0.125732421875, 0.489501953125, 0.58203125, 0.6650390625, 0.08203125, 0.231201171875, -0.93896484375, -0.9033203125, 0.029266357421875, -0.482421875, -0.58740234375, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Tags: math, number theory Correct Solution: ``` l=list(map(int,input().split())) n=l[0] k=l[1] l=[] b=[] for i in range (k): b.append(int(0)) l=list(map(int,input().split())) for i in l: b[i%k]+=1 sum=b[0]-b[0]%2 for i in range (1,(k+1)//2): sum+=(min(b[i],b[k-i])*2) if(k%2==0): sum+=b[k//2]-b[k//2]%2 print (sum) ```
19,485
[ 0.350830078125, 0.4423828125, 0.1055908203125, 0.0010728836059570312, -0.720703125, -0.497314453125, -0.1773681640625, 0.486083984375, 0.34716796875, 0.85107421875, 0.486572265625, 0.1121826171875, 0.382080078125, -0.316162109375, -0.418701171875, -0.0252227783203125, -0.57470703125,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Tags: math, number theory Correct Solution: ``` num = [0 for i in range(104)] numBoxes, girls = input().split() numBoxes = int(numBoxes) girls = int(girls) caixas = map(int, input().split()) for e in caixas: num[e%girls]+=1 qtdCaixas = 0 for i in range(1, girls): if i==girls-i: qtdCaixas += min(num[i], num[girls-i])//2*2 else: qtdCaixas += min(num[i], num[girls-i]) print(qtdCaixas+num[0]//2*2) ```
19,486
[ 0.350830078125, 0.4423828125, 0.1055908203125, 0.0010728836059570312, -0.720703125, -0.497314453125, -0.1773681640625, 0.486083984375, 0.34716796875, 0.85107421875, 0.486572265625, 0.1121826171875, 0.382080078125, -0.316162109375, -0.418701171875, -0.0252227783203125, -0.57470703125,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Tags: math, number theory Correct Solution: ``` def womens_day_problem(): n, k = input().split(' ') n, k = int(n), int(k) b = input().split(' ') for i, _ in enumerate(b): b[i] = int(b[i]) a = [] for i in range(k+1): a.append(0) for i in range(n): a[b[i] % k] += 1 cnt = a[0] // 2 if k % 2 == 0: cnt += a[k//2] // 2 for i in range((k+1)//2): tmp = min(a[i], a[k-i]) cnt += tmp a[i] -= tmp a[k-i] -= tmp print(2 * cnt) return if __name__ == '__main__': womens_day_problem() ```
19,487
[ 0.350830078125, 0.4423828125, 0.1055908203125, 0.0010728836059570312, -0.720703125, -0.497314453125, -0.1773681640625, 0.486083984375, 0.34716796875, 0.85107421875, 0.486572265625, 0.1121826171875, 0.382080078125, -0.316162109375, -0.418701171875, -0.0252227783203125, -0.57470703125,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Tags: math, number theory Correct Solution: ``` # -*- coding: utf-8 -*- import sys from collections import Counter def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(): return list(map(int, input().split())) def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10 ** 9) INF = float('inf') MOD = 10 ** 9 + 7 N,K=MAP() A=LIST() C=Counter() for i in range(N): C[A[i]%K]+=1 ans=C[0]//2 del C[0] if K%2==0: ans+=C[K//2]//2 del C[K//2] for k in sorted(C.keys()): if k>K//2: break ans+=min(C[k], C[K-k]) print(ans*2) ```
19,488
[ 0.350830078125, 0.4423828125, 0.1055908203125, 0.0010728836059570312, -0.720703125, -0.497314453125, -0.1773681640625, 0.486083984375, 0.34716796875, 0.85107421875, 0.486572265625, 0.1121826171875, 0.382080078125, -0.316162109375, -0.418701171875, -0.0252227783203125, -0.57470703125,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Tags: math, number theory Correct Solution: ``` from collections import defaultdict def main(): d = defaultdict(int) n,k = map(int, input().split()) arr = list(map(int , input().split())) for ele in arr: d[ele%k] += 1 m = 0 for key in list(d.keys()): if key == 0: if d[key] %2 == 0: m += d[key] else: m += d[key] -1 elif k-key == key: if d[key]%2 == 0: m += d[key] else: m += d[key] -1 else: l = min(d[key], d[k-key]) m += 2*l d[key] -= l d[k-key] -= l print(m) main() ```
19,489
[ 0.350830078125, 0.4423828125, 0.1055908203125, 0.0010728836059570312, -0.720703125, -0.497314453125, -0.1773681640625, 0.486083984375, 0.34716796875, 0.85107421875, 0.486572265625, 0.1121826171875, 0.382080078125, -0.316162109375, -0.418701171875, -0.0252227783203125, -0.57470703125,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Tags: math, number theory Correct Solution: ``` '''input 7 3 1 2 2 3 2 4 5 ''' import sys from collections import defaultdict as dd from itertools import permutations as pp from itertools import combinations as cc from collections import Counter as ccd from random import randint as rd from bisect import bisect_left as bl import heapq mod=10**9+7 def ri(flag=0): if flag==0: return [int(i) for i in sys.stdin.readline().split()] else: return int(sys.stdin.readline()) n,k=ri() a=ri() take=[0 for i in range(105)] nee=[0 for i in range(105)] for i in a: take[i%k]+=1 nee[i%k]+=1 ans=0 ans+=(take[0]//2)*2 for i in range(1,k): if i==k-i: ans+=(take[i]//2)*2 elif k-i>=0: #print(i,k-i) ans+=min(take[i],take[k-i]) print(ans) ```
19,490
[ 0.350830078125, 0.4423828125, 0.1055908203125, 0.0010728836059570312, -0.720703125, -0.497314453125, -0.1773681640625, 0.486083984375, 0.34716796875, 0.85107421875, 0.486572265625, 0.1121826171875, 0.382080078125, -0.316162109375, -0.418701171875, -0.0252227783203125, -0.57470703125,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Tags: math, number theory Correct Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) d = [0] * k for i in range(n): d[a[i] % k] += 1 num = 0 for i in range(k): if k - i < i: break if i == 0: num += d[i] // 2 elif i == k - i: num += d[i] // 2 else: num += min(d[i], d[k - i]) print(num * 2) ```
19,491
[ 0.350830078125, 0.4423828125, 0.1055908203125, 0.0010728836059570312, -0.720703125, -0.497314453125, -0.1773681640625, 0.486083984375, 0.34716796875, 0.85107421875, 0.486572265625, 0.1121826171875, 0.382080078125, -0.316162109375, -0.418701171875, -0.0252227783203125, -0.57470703125,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Tags: math, number theory Correct Solution: ``` n,k=map(int,input().split()) l=list(map(int,input().split())) re=[0]*101 for i in range(n): re[l[i]%k]+=1 #print(l[i]%k,re[l[i]%k]) m=0 for i in range(n): a=l[i]%k if 2*a==k: if re[k-a]>=2 and a!=0: m=m+2 #print(i) re[k-a]=re[k-a]-2 elif re[k-a]>=1 and a!=0 and re[a]>=1: m=m+2 #print(i) re[k-a]=re[k-a]-1 re[a]=re[a]-1 elif a==0 and re[0]>=2: m=m+2 #print(i) re[0]=re[0]-2 print(m) ```
19,492
[ 0.350830078125, 0.4423828125, 0.1055908203125, 0.0010728836059570312, -0.720703125, -0.497314453125, -0.1773681640625, 0.486083984375, 0.34716796875, 0.85107421875, 0.486572265625, 0.1121826171875, 0.382080078125, -0.316162109375, -0.418701171875, -0.0252227783203125, -0.57470703125,...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Submitted Solution: ``` n, k = list(map(int, input().strip().split())) d = list(map(int, input().strip().split())) mod_dict = dict() for di in d: di_mod = di % k if di_mod in mod_dict: mod_dict[di_mod] += 1 else: mod_dict[di_mod] = 1 # print(mod_dict) tot_boxes = 0 for i in range(1, k): if i in mod_dict and (k-i) in mod_dict: if i == k - i: tot_boxes += ( int(mod_dict[i] / 2) * 2 ) else: tot_boxes += min(mod_dict[i], mod_dict[k-i]) if 0 in mod_dict: tot_boxes += ( int(mod_dict[0] / 2) * 2 ) print(tot_boxes) # a = 10**14 # print(a) # print(a - 1) ``` Yes
19,493
[ 0.399658203125, 0.480224609375, 0.08428955078125, -0.0222625732421875, -0.81103515625, -0.41943359375, -0.244140625, 0.56494140625, 0.24072265625, 0.8427734375, 0.51318359375, 0.123046875, 0.28759765625, -0.35546875, -0.45947265625, -0.0105438232421875, -0.56787109375, -0.554199218...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Submitted Solution: ``` a = input().split() #length = int(a[0]) mod = int(a[1]) data = list(map(int, input().split())) dic = {} for i in range(mod): dic[i] = 0 for num in data: dic[num%mod] += 1 sum = 0 for i in range(1, (mod+1)//2): sum += min(dic[i], dic[mod - i]) sum += dic[0]//2 if mod % 2 ==0: sum += dic[mod//2]//2 print(sum*2) ``` Yes
19,494
[ 0.399658203125, 0.480224609375, 0.08428955078125, -0.0222625732421875, -0.81103515625, -0.41943359375, -0.244140625, 0.56494140625, 0.24072265625, 0.8427734375, 0.51318359375, 0.123046875, 0.28759765625, -0.35546875, -0.45947265625, -0.0105438232421875, -0.56787109375, -0.554199218...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Submitted Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) dicttotal = dict.fromkeys(range(k), 0) answer = 0 for i in range (n) : dicttotal[a[i] % k] += 1 answer += dicttotal[0] // 2 for i in range (1, (k + 1) // 2) : answer += min(dicttotal[i], dicttotal[k - i]) if k % 2 == 0 : answer += dicttotal[k / 2] // 2 print (answer * 2) ``` Yes
19,495
[ 0.399658203125, 0.480224609375, 0.08428955078125, -0.0222625732421875, -0.81103515625, -0.41943359375, -0.244140625, 0.56494140625, 0.24072265625, 0.8427734375, 0.51318359375, 0.123046875, 0.28759765625, -0.35546875, -0.45947265625, -0.0105438232421875, -0.56787109375, -0.554199218...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Submitted Solution: ``` z,zz=input,lambda:list(map(int,z().split())) n,k=zz() lst=zz() cnt=[0]*k for i in lst:cnt[i%k]+=1 ans=cnt[0]//2 l=1 r=k-1 while l<r: ans+=min(cnt[l],cnt[r]) l+=1 r-=1 if k%2==0: ans+=cnt[k//2]//2 print(ans*2) ``` Yes
19,496
[ 0.399658203125, 0.480224609375, 0.08428955078125, -0.0222625732421875, -0.81103515625, -0.41943359375, -0.244140625, 0.56494140625, 0.24072265625, 0.8427734375, 0.51318359375, 0.123046875, 0.28759765625, -0.35546875, -0.45947265625, -0.0105438232421875, -0.56787109375, -0.554199218...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Submitted Solution: ``` n,k=[int(x) for x in input().split()] a=list(map(int,input().split())) d=dict() d[0]=0 for i in range(0,101): d[i]=0 for i in range(n): a[i]%=k d[a[i]]+=1 ans=0 for i in range(0,k): if a[i]==0: ans+=(d[0]//2)*2 if(d[0]): d[0]=0 else: d[0]=1 continue if d[k-a[i]]: d[k-a[i]]-=1 d[a[i]]-=1 ans+=2 print(ans) ``` No
19,497
[ 0.399658203125, 0.480224609375, 0.08428955078125, -0.0222625732421875, -0.81103515625, -0.41943359375, -0.244140625, 0.56494140625, 0.24072265625, 0.8427734375, 0.51318359375, 0.123046875, 0.28759765625, -0.35546875, -0.45947265625, -0.0105438232421875, -0.56787109375, -0.554199218...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Submitted Solution: ``` n, k = map(int, input().split()) l = map (int, input().split()) f = [0 for i in range(0, k)] for i in l: f[i%k]=f[i%k]+1 ans = f[0]//2 for i in range(1, k//2+1): ans=ans+min(f[i], f[k-i]) print(2*ans) ``` No
19,498
[ 0.399658203125, 0.480224609375, 0.08428955078125, -0.0222625732421875, -0.81103515625, -0.41943359375, -0.244140625, 0.56494140625, 0.24072265625, 0.8427734375, 0.51318359375, 0.123046875, 0.28759765625, -0.35546875, -0.45947265625, -0.0105438232421875, -0.56787109375, -0.554199218...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Submitted Solution: ``` n, k = map(int, input().split()) liczby = list(map(int, input().split())) lista = [] wynik = 0 zera = 0 for x in range(n): reszta = liczby[x] % k lista.append(reszta) lista.sort() slownik = {} a = 1 for x in range(n-1): if lista[x] == lista[x+1]: a+=1 if x == n-2: if lista[x] == 0: zera += a else: slownik[lista[x]] = a else: if lista[x] == 0: zera += a else: slownik[lista[x]] = a a = 1 x = 1 y = k-1 while x <= y: if x + y == k: try: if x != y: wynik+= min(slownik[x], slownik[y]) y-=1 x+=1 else: wynik+= slownik[x] // 2 x+=1 except: x+=1 elif x + y > k: y-=1 else: x+=1 wynik+= zera // 2 print(2*wynik) #1 2 4 6 8 == 10 ``` No
19,499
[ 0.399658203125, 0.480224609375, 0.08428955078125, -0.0222625732421875, -0.81103515625, -0.41943359375, -0.244140625, 0.56494140625, 0.24072265625, 0.8427734375, 0.51318359375, 0.123046875, 0.28759765625, -0.35546875, -0.45947265625, -0.0105438232421875, -0.56787109375, -0.554199218...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i β‰  j) can be combined as a gift if d_i + d_j is divisible by k. How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. Input The first line of the input contains two integers n and k (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ k ≀ 100) β€” the number the boxes and the number the girls. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≀ d_i ≀ 10^9), where d_i is the number of candies in the i-th box. Output Print one integer β€” the maximum number of the boxes Polycarp can give as gifts. Examples Input 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 Note In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (2, 3); * (5, 6); * (1, 4). So the answer is 6. In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (6, 8); * (2, 3); * (1, 4); * (5, 7). So the answer is 8. In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): * (1, 2); * (6, 7). So the answer is 4. Submitted Solution: ``` n,k=map(int,input().split()) b=[0]*(k+1) s=list(map(int,input().split())) for z in s: b[z%k]+=1 if k==1: print(0) exit() del s count=(b[0]//2)*2 for i in range(1,len(b)//2+1): count+=min(b[i],b[k-i]) print(count) ``` No
19,500
[ 0.399658203125, 0.480224609375, 0.08428955078125, -0.0222625732421875, -0.81103515625, -0.41943359375, -0.244140625, 0.56494140625, 0.24072265625, 0.8427734375, 0.51318359375, 0.123046875, 0.28759765625, -0.35546875, -0.45947265625, -0.0105438232421875, -0.56787109375, -0.554199218...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Tags: math, number theory Correct Solution: ``` #import math #from functools import lru_cache #import heapq #from collections import defaultdict #from collections import Counter #from sys import stdout #from sys import setrecursionlimit from sys import stdin input = stdin.readline for Ti in range(int(input().strip())): n, k = [int(x) for x in input().strip().split()] i = 1 a = float('inf') while(i*i<=n and i<=k): rem, div = n%i, n//i if(not rem): if(div<=k): a = min(a, i) a = min(a, div) i+=1 print(a) ```
19,592
[ 0.57958984375, 0.270263671875, 0.31396484375, 0.017059326171875, -0.7373046875, -0.2005615234375, -0.095458984375, 0.117919921875, 0.09033203125, 0.88525390625, 0.92578125, 0.08013916015625, 0.4873046875, -0.55712890625, -0.54833984375, 0.533203125, -0.611328125, -0.69775390625, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Tags: math, number theory Correct Solution: ``` from math import sqrt def divisors(n): divs = {1} for i in range(2, int(sqrt(n)) + 5): if n % i == 0: divs.add(i) divs.add(n // i) divs |= {n} return divs def main(): n, k = map(int, input().split()) ans = 1e18 for div in divisors(n): if div <= k: ans = min(ans, n // div) return ans if __name__ == "__main__": t = int(input()) for _ in range(t): print(main()) ```
19,593
[ 0.55126953125, 0.25732421875, 0.317138671875, -0.0218505859375, -0.68896484375, -0.200439453125, -0.02203369140625, 0.1435546875, 0.0997314453125, 0.91845703125, 0.97216796875, 0.0877685546875, 0.4775390625, -0.537109375, -0.484130859375, 0.493408203125, -0.63720703125, -0.63623046...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Tags: math, number theory Correct Solution: ``` from sys import stdin,stdout for query in range(int(stdin.readline())): nk=stdin.readline().split() n=int(nk[0]) k=int(nk[1]) lowest=10000000000 mybool=False count=0 for x in range(1,int(n**.5)+1): count+=1 if n%x==0: if n//x<=k: stdout.write(str(x)+'\n') mybool=True break if x<=k: lowest=n//x if mybool: continue stdout.write(str(lowest)+'\n') ```
19,594
[ 0.57470703125, 0.250732421875, 0.303955078125, 0.0276336669921875, -0.74609375, -0.275146484375, -0.04705810546875, 0.176025390625, 0.056671142578125, 0.919921875, 0.953125, 0.0911865234375, 0.4482421875, -0.57421875, -0.54931640625, 0.469482421875, -0.57421875, -0.64013671875, -...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Tags: math, number theory Correct Solution: ``` import math for i1 in range(int(input())): n,k=map(int,input().split()) root=int(math.sqrt(n)) if k>=n: print(1) continue lim=min(k,root) #print('lim',lim) flag=0 for i in range(2,lim+1): if n%i==0: flag=1 temp=n//i if temp<=k: temp=i break if flag: print(temp) else: print(n) ```
19,595
[ 0.564453125, 0.246826171875, 0.30126953125, -0.01861572265625, -0.654296875, -0.2322998046875, 0.01248931884765625, 0.18359375, 0.08099365234375, 0.943359375, 0.97705078125, 0.09075927734375, 0.43505859375, -0.6025390625, -0.482421875, 0.53466796875, -0.56201171875, -0.6328125, -...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Tags: math, number theory Correct Solution: ``` testcases = int( input() ) import math for testcase in range(testcases): newarr = input() newarr = newarr.split() n = int(newarr[0]) k = int(newarr[1]) if k >= n: print(1) continue if n % k == 0 : print( n // k) continue if k == 2 and n & 1 == 1 : print(n) continue if k == 3 and n & 1 == 0 : print(n // 2) continue sqrtans = int(math.sqrt(n)) + 3 ans = n #print("sqrtans is" + str(sqrtans)) for i in range( 2, min(k + 1, sqrtans) ): if n % i == 0 : ans = n // i if ans <= k : ans = i break print(ans) ```
19,596
[ 0.58935546875, 0.263427734375, 0.281005859375, -0.037078857421875, -0.70947265625, -0.306396484375, 0.00043582916259765625, 0.1865234375, 0.09625244140625, 0.89501953125, 0.998046875, 0.08447265625, 0.482421875, -0.6103515625, -0.49853515625, 0.4765625, -0.5869140625, -0.6528320312...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Tags: math, number theory Correct Solution: ``` def f(n,k): x = 1 while x*x <=n: if n%x == 0 and n/x <= k: return x x+=1 ans = 0 y = 1 while y*y <=n: if n%y == 0 and y<=k: ans = n//y y+=1 return ans t = int(input()) for i in range(t): [n,k] = input().split(' ') n = int(n) k = int(k) print(f(n,k)) ```
19,597
[ 0.556640625, 0.2479248046875, 0.3193359375, 0.00920867919921875, -0.7099609375, -0.26220703125, -0.016876220703125, 0.172119140625, 0.08123779296875, 0.89990234375, 0.994140625, 0.10076904296875, 0.48583984375, -0.556640625, -0.52783203125, 0.509765625, -0.62646484375, -0.646972656...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Tags: math, number theory Correct Solution: ``` import math def checkprime(n): for i in range(2,int(math.sqrt(n))+1): if(n%i==0): return False return True def fctrlist(n): L = [] for i in range(2,int(n**0.5)+1): if(n%i==0): if(n//i == i): L.append(i) else: L.append(n//i);L.append(i) return L # Priyanshu Kumar for _ in range(int(input())): n,k = map(int,input().split()) if(k==1): print(n) continue if(n<=k): print(1) continue if(checkprime(n)): print(n) continue A = fctrlist(n) A.sort() i = 0 d = 1 while(i<len(A)): if(n//A[i] <= k): d = n//A[i] break else: i+=1 print(int(n//d)) ```
19,598
[ 0.5458984375, 0.22900390625, 0.311279296875, 0.0166778564453125, -0.66015625, -0.2435302734375, 0.0010013580322265625, 0.1748046875, 0.10986328125, 0.92138671875, 1.021484375, 0.091552734375, 0.484619140625, -0.58642578125, -0.5087890625, 0.509765625, -0.60400390625, -0.63671875, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Tags: math, number theory Correct Solution: ``` import math for _ in range(int(input())): n, k = list(map(int,input().split())) res = n for i in range(1, int(math.sqrt(n))+1): if n % i == 0: if n // i <= k and i <= res: res = i elif i <= k and n // i <= res: res = n // i print(res) ```
19,599
[ 0.55517578125, 0.229736328125, 0.29443359375, -0.0193328857421875, -0.67431640625, -0.248046875, -0.004241943359375, 0.1676025390625, 0.059600830078125, 0.939453125, 1.005859375, 0.0849609375, 0.461669921875, -0.5908203125, -0.50439453125, 0.51025390625, -0.603515625, -0.6416015625...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Submitted Solution: ``` t=int(input()) import math def factors(n,k): results = set() for i in range(1, int(math.sqrt(n)) + 1): if n % i == 0 and i<=k: results.add(i) last=int(n/i) if last <=k: results.add(int(n/i)) return results for test in range(t): n,k=[int(x) for x in input().split()] high=1 if n <= k: print(1) continue ans=list(factors(n,k)) ans.sort() print(n//ans[-1]) ``` Yes
19,600
[ 0.60595703125, 0.284423828125, 0.22119140625, -0.0108642578125, -0.82666015625, -0.1329345703125, -0.08770751953125, 0.209716796875, 0.10137939453125, 0.91015625, 0.9482421875, 0.1251220703125, 0.405517578125, -0.677734375, -0.525390625, 0.369384765625, -0.61767578125, -0.659179687...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Submitted Solution: ``` import math T = int(input()) def divs(n): d = [] for i in range(1, math.ceil(math.sqrt(n))+1): if n % i == 0: d.extend([i, n//i]) return sorted(d) for t in range(T): N, K = [int(_) for _ in input().split()] for d in divs(N): if N / d <= K: print(d) break ``` Yes
19,601
[ 0.5830078125, 0.30078125, 0.22314453125, -0.0103607177734375, -0.84716796875, -0.10247802734375, -0.0965576171875, 0.2447509765625, 0.11993408203125, 0.92333984375, 0.951171875, 0.1280517578125, 0.39794921875, -0.62841796875, -0.5439453125, 0.3818359375, -0.61279296875, -0.63671875...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Submitted Solution: ``` import sys def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def get_ints(): return map(int, sys.stdin.readline().strip().split()) def input(): return sys.stdin.readline().strip() import math # method to print the divisors def div(n): # Note that this loop runs till square root i = 1 c = [] while i <= math.sqrt(n): if (n % i == 0): # If divisors are equal, print only one if (n / i == i): c.append(i) else: # Otherwise print both c.append(i) c.append(n // i) i = i + 1 return (list(set(c))) for _ in range(int(input())): n, k = map(int, input().split()) li = div(n) li.sort() d=[] for i in range(len(li)): if li[i] > k: break d.append(n // li[i]) print(min(d)) ``` Yes
19,602
[ 0.60546875, 0.25390625, 0.2568359375, 0.000732421875, -0.8857421875, -0.1466064453125, -0.139892578125, 0.235107421875, 0.1011962890625, 0.90966796875, 0.91357421875, 0.099853515625, 0.434326171875, -0.60546875, -0.55712890625, 0.343994140625, -0.59228515625, -0.615234375, -0.745...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Submitted Solution: ``` import math t=int(input()) for j in range(t): n,k=map(int,input().split()) max=1 if n<=k: print("1") else: for i in range(1,int(math.sqrt(n))+1): if n%i==0: if i<=k: if max<=i: max=i if n//i<=k: if max<n//i: max=n//i print(n//max) ``` Yes
19,603
[ 0.5849609375, 0.29345703125, 0.2054443359375, -0.007480621337890625, -0.82861328125, -0.14111328125, -0.06878662109375, 0.2423095703125, 0.1131591796875, 0.951171875, 0.9638671875, 0.1402587890625, 0.400634765625, -0.669921875, -0.54443359375, 0.38623046875, -0.62158203125, -0.6406...
24
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Submitted Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write mod=10**9+7 def ni(): return int(raw_input()) def li(): return map(int,raw_input().split()) def pn(n): stdout.write(str(n)+'\n') def pa(arr): pr(' '.join(map(str,arr))+'\n') # fast read function for total integer input def inp(): # this function returns whole input of # space/line seperated integers # Use Ctrl+D to flush stdin. return map(int,stdin.read().split()) range = xrange # not for python 3.0+ # main code for t in range(input()): n,k=li() i=2 ans=1 if n<=k: pn(1) continue while i*i<=n: if n%i==0: x1=i x2=n/i if x1<=k: ans=max(ans,x1) if x2<=k: ans=max(ans,x2) i+=1 pn(n/ans) ``` Yes
19,604
[ 0.5341796875, 0.3076171875, 0.269775390625, 0.038360595703125, -0.93115234375, -0.1671142578125, -0.2298583984375, 0.2269287109375, 0.12445068359375, 0.9716796875, 0.90087890625, 0.09661865234375, 0.42724609375, -0.54931640625, -0.56884765625, 0.4140625, -0.61474609375, -0.69238281...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Submitted Solution: ``` from math import sqrt if __name__ == '__main__': t = int(input()) for _ in range(t): n, k = map(int, input().split()) if k >= n: print(1) continue i = min(int(sqrt(n)) + 1, k) while i > 0: if n % i == 0: m = min(n//i, i) M = max(n//i, i) print(m if M <= k else M) break i -= 1 else: print(n) ``` No
19,605
[ 0.59716796875, 0.29296875, 0.2158203125, -0.0117950439453125, -0.84130859375, -0.107177734375, -0.10174560546875, 0.2265625, 0.1102294921875, 0.9091796875, 0.97509765625, 0.1065673828125, 0.375732421875, -0.640625, -0.54541015625, 0.38330078125, -0.6298828125, -0.6328125, -0.6689...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Submitted Solution: ``` def isPrime(n): if (n <= 1): return False if (n <= 3): return True if (n % 2 == 0 or n % 3 == 0): return False i = 5 while (i * i <= n): if (n % i == 0 or n % (i + 2) == 0): return False i = i + 6 return True answer = [] for i in range(int(input())): n, k = list(map(int, input().split())) if k >= n: answer.append(1) elif k == 1: answer.append(n) else: if not isPrime(n): for j in range(2, k + 1): if n % j == 0: answer.append(j) break else: answer.append(n) for i in range(len(answer)): print(answer[i]) ``` No
19,606
[ 0.58642578125, 0.278564453125, 0.2255859375, 0.016265869140625, -0.791015625, -0.1622314453125, -0.09234619140625, 0.1964111328125, 0.1729736328125, 0.92578125, 0.99658203125, 0.1181640625, 0.44775390625, -0.67578125, -0.5185546875, 0.388671875, -0.6298828125, -0.611328125, -0.65...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Submitted Solution: ``` import math for _ in range(int(input())): n, k = map(int, input().split()) if k >= n: print(1) else: j = 1 ans = n while j * j < n: if n % j == 0: if j < k: ans = min(ans, n// j) if n // j < k: ans = min(ans, j) j += 1 print(ans) ``` No
19,607
[ 0.58349609375, 0.296630859375, 0.2373046875, -0.001750946044921875, -0.8408203125, -0.1605224609375, -0.0819091796875, 0.2509765625, 0.10321044921875, 0.94482421875, 0.98193359375, 0.12103271484375, 0.39404296875, -0.65966796875, -0.55078125, 0.3955078125, -0.63525390625, -0.643554...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly n shovels? For example, if n=8 and k=7, then Polycarp will buy 2 packages of 4 shovels. Help Polycarp find the minimum number of packages that he needs to buy, given that he: * will buy exactly n shovels in total; * the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from 1 to k, inclusive. Input The first line contains an integer t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then, t test cases follow, one per line. Each test case consists of two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 10^9) β€” the number of shovels and the number of types of packages. Output Print t answers to the test cases. Each answer is a positive integer β€” the minimum number of packages. Example Input 5 8 7 8 1 6 10 999999733 999999732 999999733 999999733 Output 2 8 1 999999733 1 Note The answer to the first test case was explained in the statement. In the second test case, there is only one way to buy 8 shovels β€” 8 packages of one shovel. In the third test case, you need to buy a 1 package of 6 shovels. Submitted Solution: ``` #!/usr/bin/env python3 # vim: set fileencoding=utf-8 # pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation """Module docstring """ import functools import heapq import itertools import logging import math import os import random import string import sys from argparse import ArgumentParser from collections import defaultdict, deque from copy import deepcopy from io import BytesIO, IOBase from typing import Dict, List, Optional, Set, Tuple def solve(n: int, k: int) -> int: if n <= k: return 1 for i in range(max(2, math.ceil(n / k)), min(k, math.ceil(math.sqrt(n))) + 1): if n % i == 0: return i return n def do_job(stdin, stdout): "Do the work" LOG.debug("Start working") # first line is number of test cases T = int(stdin.readline().strip()) for _testcase in range(T): n, k = map(int, stdin.readline().split()) result = solve(n, k) print(result, file=stdout) def print_output(testcase: int, result) -> None: "Formats and print result" if result is None: result = "IMPOSSIBLE" print("Case #{}: {}".format(testcase + 1, result)) # 6 digits float precision {:.6f} (6 is the default value) # print("Case #{}: {:f}".format(testcase + 1, result)) BUFSIZE = 8192 class FastIO(IOBase): # pylint: disable=super-init-not-called, expression-not-assigned 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): # pylint: disable=super-init-not-called 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") def configure_log() -> None: "Configure the log output" log_formatter = logging.Formatter("L%(lineno)d - " "%(message)s") handler = logging.StreamHandler(IOWrapper(sys.stderr)) handler.setFormatter(log_formatter) LOG.addHandler(handler) LOG = None # for interactive call: do not add multiple times the handler if not LOG: LOG = logging.getLogger("template") configure_log() def main(argv=None): "Program wrapper." if argv is None: argv = sys.argv[1:] parser = ArgumentParser() parser.add_argument( "-v", "--verbose", dest="verbose", action="store_true", default=False, help="run as verbose mode", ) args = parser.parse_args(argv) if args.verbose: LOG.setLevel(logging.DEBUG) stdin = IOWrapper(sys.stdin) stdout = IOWrapper(sys.stdout) do_job(stdin, stdout) stdout.flush() for h in LOG.handlers: h.flush() return 0 if __name__ == "__main__": sys.exit(main()) ``` No
19,608
[ 0.62744140625, 0.278076171875, 0.27099609375, 0.02716064453125, -0.89404296875, -0.1727294921875, -0.13623046875, 0.2030029296875, 0.159423828125, 0.9306640625, 0.8193359375, 0.08929443359375, 0.41943359375, -0.5732421875, -0.5537109375, 0.370361328125, -0.5908203125, -0.642578125,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Tags: implementation, math Correct Solution: ``` import math def get_lcm(n1, n2): # find gcd gcd = math.gcd(n1, n2) # formula result = (n1 * n2) / gcd return result class CodeforcesTask173ASolution: def __init__(self): self.result = '' self.rounds = 0 self.n_str = '' self.p_str = '' def read_input(self): self.rounds = int(input()) self.n_str = input() self.p_str = input() def process_task(self): n = int(len(self.n_str)) k = int(len(self.p_str)) ap = 0 bp = 0 np = 0 pp = 0 full_round = int(get_lcm(n, k)) if self.rounds <= full_round: for x in range(self.rounds): a = self.n_str[ap] b = self.p_str[bp] ap += 1 bp += 1 if ap >= n: ap = 0 if bp >= k: bp = 0 if (a == "R" and b == "S") or (a == "S" and b == "P") or (a == "P" and b == "R"): pp += 1 elif (b == "R" and a == "S") or (b == "S" and a == "P") or (b == "P" and a == "R"): np += 1 self.result = "{0} {1}".format(np, pp) else: for x in range(full_round): a = self.n_str[ap] b = self.p_str[bp] ap += 1 bp += 1 if ap >= n: ap = 0 if bp >= k: bp = 0 if (a == "R" and b == "S") or (a == "S" and b == "P") or (a == "P" and b == "R"): pp += 1 elif (b == "R" and a == "S") or (b == "S" and a == "P") or (b == "P" and a == "R"): np += 1 np *= self.rounds // full_round pp *= self.rounds // full_round for x in range(self.rounds % full_round): a = self.n_str[ap] b = self.p_str[bp] ap += 1 bp += 1 if ap >= n: ap = 0 if bp >= k: bp = 0 if (a == "R" and b == "S") or (a == "S" and b == "P") or (a == "P" and b == "R"): pp += 1 elif (b == "R" and a == "S") or (b == "S" and a == "P") or (b == "P" and a == "R"): np += 1 self.result = "{0} {1}".format(np, pp) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask173ASolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
19,689
[ 0.154052734375, 0.055633544921875, 0.2474365234375, 0.32568359375, -0.52587890625, -0.399169921875, -0.292236328125, 0.018280029296875, 0.03216552734375, 0.580078125, 1.015625, -0.11083984375, 0.37109375, -0.2403564453125, -0.478515625, -0.205810546875, -0.89990234375, -0.788085937...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Tags: implementation, math Correct Solution: ``` Q=lambda x,y:Q(y%x,x)if x else y I=input R=range n=int(I()) s=I() p=I() G=len(p)//Q(len(s),len(p))*len(s) s*=G//len(s) p*=G//len(p) a=b=0 for i in R(G): t=s[i]+p[i] if t=='RS'or t=='SP'or t=='PR':a+=1 elif t=='SR'or t=='PS' or t=='RP':b+=1 a*=(n//G) b*=(n//G) for i in R(n%G): t=s[i]+p[i] if t=='RS'or t=='SP'or t=='PR':a+=1 elif t=='SR'or t=='PS' or t=='RP':b+=1 print(b,a) ```
19,690
[ 0.154052734375, 0.055633544921875, 0.2474365234375, 0.32568359375, -0.52587890625, -0.399169921875, -0.292236328125, 0.018280029296875, 0.03216552734375, 0.580078125, 1.015625, -0.11083984375, 0.37109375, -0.2403564453125, -0.478515625, -0.205810546875, -0.89990234375, -0.788085937...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Tags: implementation, math Correct Solution: ``` n = int(input()) a = input() b = input() ai = 0 alen = len(a) bi = 0 blen = len(b) nik = 0 pol = 0 if alen == blen: rnd = alen else: rnd = alen*blen numofrounds = 0 for i in range(n): #print(i,rnd) if i == rnd: numofrounds = n//rnd # print(numofrounds) nik *= numofrounds pol *= numofrounds break #print(a[ai%alen], b[bi%blen]) if a[ai] == b[bi]: pass elif (a[ai] == 'R' and b[bi] == 'S') or (a[ai] == 'S' and b[bi] == 'P') or (a[ai] == 'P' and b[bi] == 'R'): pol += 1 else: nik += 1 ai = (ai+1)%alen bi = (bi+1)%blen if n%rnd != 0 and numofrounds != 0: n -= rnd*numofrounds ai = 0 bi = 0 for i in range(n): if a[ai] == b[bi]: pass elif (a[ai] == 'R' and b[bi] == 'S') or (a[ai] == 'S' and b[bi] == 'P') or (a[ai] == 'P' and b[bi] == 'R'): pol += 1 else: nik += 1 ai = (ai+1)%alen bi = (bi+1)%blen print(nik, pol) ```
19,691
[ 0.154052734375, 0.055633544921875, 0.2474365234375, 0.32568359375, -0.52587890625, -0.399169921875, -0.292236328125, 0.018280029296875, 0.03216552734375, 0.580078125, 1.015625, -0.11083984375, 0.37109375, -0.2403564453125, -0.478515625, -0.205810546875, -0.89990234375, -0.788085937...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Tags: implementation, math Correct Solution: ``` def gcd(a, b): c = a % b return gcd(b, c) if c else b def f(k, m, n): p = {} for i in range(m * k + 1, 0, -k): j = m - (i - 1 - n) % m for d in range(j - n, n, m): p[d] = i return p n, a, b = int(input()), input(), input() k, m = len(a), len(b) x, y, g = 0, 0, gcd(k, m) p, q, r = (k * m) // g, f(k, m, 1000), {'S': 'P', 'P': 'R', 'R': 'S'} for i in range(k): for j in range(i % g, m, g): if a[i] == b[j]: continue d = (n - q[i - j] - i) // p + 1 if r[a[i]] == b[j]: y += d else: x += d print(x, y) ```
19,692
[ 0.154052734375, 0.055633544921875, 0.2474365234375, 0.32568359375, -0.52587890625, -0.399169921875, -0.292236328125, 0.018280029296875, 0.03216552734375, 0.580078125, 1.015625, -0.11083984375, 0.37109375, -0.2403564453125, -0.478515625, -0.205810546875, -0.89990234375, -0.788085937...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Tags: implementation, math Correct Solution: ``` n=int(input()) aa,bb=0,0 a=list(input()) b=list(input()) rp=[] i=0 while( 1 ): if a[i%len(a)]=="R": if b[i%len(b)]=="P": bb+=1 elif b[i%len(b)]=="S": aa+=1 elif a[i%len(a)]=="P": if b[i%len(b)]=="R": aa+=1 elif b[i%len(b)]=="S": bb+=1 else: if b[i%len(b)]=="R": bb+=1 elif b[i%len(b)]=="P": aa+=1 i+=1 rp.append( (bb,aa) ) if ( i%len(a)==0 and i%len(b)==0 ) or i>n: break if len(rp)==n: print(bb,aa) else: w = n//len(rp) ww = n%len(rp) if ww==0: print( bb*w, aa*w ) else: print( bb*w+rp[ww-1][0], aa*w+rp[ww-1][1] ) ```
19,693
[ 0.154052734375, 0.055633544921875, 0.2474365234375, 0.32568359375, -0.52587890625, -0.399169921875, -0.292236328125, 0.018280029296875, 0.03216552734375, 0.580078125, 1.015625, -0.11083984375, 0.37109375, -0.2403564453125, -0.478515625, -0.205810546875, -0.89990234375, -0.788085937...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Tags: implementation, math Correct Solution: ``` import sys rounds=int(sys.stdin.readline().strip('\n')) def Solution(): global rounds s_A=list(map(str, sys.stdin.readline().rstrip('\n'))) s_B=list(map(str, sys.stdin.readline().rstrip('\n'))) if rounds<=len(s_A): s_A=s_A[0:rounds] if rounds<len(s_B): s_B=s_B[0:rounds] return Prepare(s_A, s_B) return Prepare(s_A, s_B) elif rounds<len(s_B): s_B=s_B[0:rounds] if rounds<len(s_B): s_A=s_A[0:rounds] return Prepare(s_A, s_B) return Prepare(s_A, s_B) else: return Prepare(s_A, s_B) def Prepare(s_A, s_B): if len(s_A)==len(s_B): return Compare(s_A, s_B) else: if len(s_A)>len(s_B): greater = len(s_A) else: greater = len(s_B) while(True): if((greater % len(s_A) == 0) and (greater % len(s_B) == 0)): lcm = greater break greater += 1 Alcm=lcm//len(s_A) Blcm=lcm//len(s_B) return Compare(s_A*Alcm, s_B*Blcm) def Compare(s_A, s_B): global rounds zipped=list(zip(s_A, s_B)) Nikephoros=0 Polycarpus=0 mult=1 for i in range (0, len(zipped)): if rounds==i: return print (Polycarpus*mult, Nikephoros*mult) elif zipped[i][0]==zipped[i][1]: pass elif (zipped[i][0]=="S" and zipped[i][1]=="P") or \ (zipped[i][0]=="R" and zipped[i][1]=="S") or \ (zipped[i][0]=="P" and zipped[i][1]=="R"): Nikephoros+=1 else: Polycarpus+=1 if rounds%len(zipped)==0: mult=rounds//len(zipped) print (Polycarpus*mult, Nikephoros*mult) else: mult=rounds//len(zipped) Nikephoros_add=0 Polycarpus_add=0 fraction=rounds - (len(zipped)*mult) iter=0 for i in range (0, len(zipped)): if iter==fraction: return print(Polycarpus*mult + Polycarpus_add, Nikephoros*mult+ Nikephoros_add) elif zipped[i][0]==zipped[i][1]: iter+=1 pass elif (zipped[i][0]=="S" and zipped[i][1]=="P") or \ (zipped[i][0]=="R" and zipped[i][1]=="S") or \ (zipped[i][0]=="P" and zipped[i][1]=="R"): Nikephoros_add+=1 iter+=1 else: Polycarpus_add+=1 iter+=1 Solution() ```
19,694
[ 0.154052734375, 0.055633544921875, 0.2474365234375, 0.32568359375, -0.52587890625, -0.399169921875, -0.292236328125, 0.018280029296875, 0.03216552734375, 0.580078125, 1.015625, -0.11083984375, 0.37109375, -0.2403564453125, -0.478515625, -0.205810546875, -0.89990234375, -0.788085937...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Tags: implementation, math Correct Solution: ``` import math import itertools as it n = int(input()) a, b = input(), input() lcm = len(a) // math.gcd(len(a), len(b)) * len(b) a, b = it.cycle(a), it.cycle(b) res = {'RR': 0, 'SS': 0, 'PP': 0, 'RS': 'P', 'SP': 'P', 'PR': 'P', 'RP': 'N', 'SR': 'N', 'PS': 'N'} v = [] for i in range(min(lcm, n)): v.append(res[next(a) + next(b)]) ans = [v.count('N'), v.count('P')] if n > lcm: ans[0] *= n // lcm ans[0] += v[: n % lcm].count('N') ans[1] *= n // lcm ans[1] += v[: n % lcm].count('P') print(*ans) ```
19,695
[ 0.154052734375, 0.055633544921875, 0.2474365234375, 0.32568359375, -0.52587890625, -0.399169921875, -0.292236328125, 0.018280029296875, 0.03216552734375, 0.580078125, 1.015625, -0.11083984375, 0.37109375, -0.2403564453125, -0.478515625, -0.205810546875, -0.89990234375, -0.788085937...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Tags: implementation, math Correct Solution: ``` n=int(input()) finale=[] co=0;fco=0; s=input() s1=input() ssize=len(s) s1size=len(s1) s=s1size*s s1=ssize*s1 for i in range(0,len(s)): if (s[i]=='R' and s1[i]=='P'): fco+=1 if (s[i]=='R' and s1[i]=='S'): co+=1 if (s[i]=='S' and s1[i]=='P'): co+=1 if (s[i]=='S' and s1[i]=='R'): fco+=1 if (s[i]=='P' and s1[i]=='S'): fco+=1 if (s[i]=='P' and s1[i]=='R'): co+=1 finale.append((co,fco)) if(len(s)>=n): co1=finale[n-1][0] fco1=finale[n-1][1] else: co1=n//len(s); co1*=finale[len(s)-1][0] if n%len(s)!=0: co1+=finale[((n)%(len(s)))-1][0] fco1=n//len(s); fco1*=finale[len(s)-1][1] if n%len(s)!=0: fco1+=finale[((n)%(len(s)))-1][1] print(fco1," ",co1) ```
19,696
[ 0.154052734375, 0.055633544921875, 0.2474365234375, 0.32568359375, -0.52587890625, -0.399169921875, -0.292236328125, 0.018280029296875, 0.03216552734375, 0.580078125, 1.015625, -0.11083984375, 0.37109375, -0.2403564453125, -0.478515625, -0.205810546875, -0.89990234375, -0.788085937...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Submitted Solution: ``` def gcd(a, b): c = a % b return gcd(b, c) if c else b F = {} def f(k, m, i, j): global F d = i - j if d in F: return F[d] + i u, v = i, d while d: if d < 0: d += k i += k else: d -= m i += 1 F[v] = i - u return i n, a, b = int(input()), input(), input() k, m = len(a), len(b) r = gcd(k, m) p = (k * m) // r x, y = 0, 0 for i in range(k): for j in range(i % r, m, r): if a[i] == b[j]: continue d = (n - f(k, m, i, j)) // p + 1 if a[i] + b[j] in ['SP', 'PR', 'RS']: y += d else: x += d print(x, y) ``` Yes
19,697
[ 0.282470703125, 0.130859375, 0.2147216796875, 0.2030029296875, -0.572265625, -0.316650390625, -0.311767578125, 0.0648193359375, 0.05914306640625, 0.63916015625, 0.87353515625, -0.07330322265625, 0.336669921875, -0.27001953125, -0.436767578125, -0.1778564453125, -0.85498046875, -0.7...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Submitted Solution: ``` #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now---------------------------------------------------- def rps(x,y): res=0 if x==y: res=0 elif x=='R' and y=='S': res=1 elif x=='S' and y=='P': res=1 elif x=='P' and y=='R': res=1 elif x=='R' and y=='P': res=2 elif x=='S' and y=='R': res=2 elif x=='P' and y=='S': res=2 return res n=int(input()) a=input() b=input() l1=len(a) l2=len(b) #print(a,b) lcm=l1*l2//math.gcd(l1,l2) c1=0 c2=0 for i in range (min(n,lcm)): x=a[i%l1] y=b[i%l2] r=0 r=rps(x, y) #print(r) if r==1: c1+=1 elif r==2: c2+=1 #print(c2,c1) if lcm<n: t=n//lcm c1*=t c2*=t t=n%lcm #print(c2,c1) for i in range (t): x=a[i%l1] y=b[i%l2] r=0 r=rps(x, y) if r==1: c1+=1 elif r==2: c2+=1 print(c2,c1) ``` Yes
19,698
[ 0.282470703125, 0.130859375, 0.2147216796875, 0.2030029296875, -0.572265625, -0.316650390625, -0.311767578125, 0.0648193359375, 0.05914306640625, 0.63916015625, 0.87353515625, -0.07330322265625, 0.336669921875, -0.27001953125, -0.436767578125, -0.1778564453125, -0.85498046875, -0.7...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Submitted Solution: ``` def co(x,y,s): if x==y:return 0 z=(x=="P" and y=="R") or (x=="S" and y=="P") or (x=="R" and y=="S") if s:return int(z) return int(not z) from math import gcd as gh a=int(input());b=input();c=input() b1=len(b);c1=len(c) z=((b1*c1)//gh(b1,c1)) w=[0]*(z+1);w1=[0]*(z+1) for i in range(1,z+1): w[i]=co(b[(i-1)%b1],c[(i-1)%c1],0)+w[i-1] w1[i]=co(b[(i-1)%b1],c[(i-1)%c1],1)+w1[i-1] print(w[-1]*(a//z)+w[a%z],w1[-1]*(a//z)+w1[a%z]) ``` Yes
19,699
[ 0.282470703125, 0.130859375, 0.2147216796875, 0.2030029296875, -0.572265625, -0.316650390625, -0.311767578125, 0.0648193359375, 0.05914306640625, 0.63916015625, 0.87353515625, -0.07330322265625, 0.336669921875, -0.27001953125, -0.436767578125, -0.1778564453125, -0.85498046875, -0.7...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Submitted Solution: ``` n=int(input()) a=input() b=input() l,r=0,0 nike=0 poly=0 if len(a)*len(b)>n: for i in range(n): x=a[l%(len(a))] y=b[r%(len(b))] if x==y: l+=1 r+=1 continue else: #print(0) if x=="R": if y=="P": nike+=1 else: poly+=1 elif x=="P": if y=="S": nike+=1 else: poly+=1 else: if y=="R": nike+=1 else: poly+=1 l+=1 r+=1 else: for i in range(len(a)*len(b)): x=a[l%(len(a))] y=b[r%(len(b))] if x==y: l+=1 r+=1 continue else: if x=="R": if y=="P": nike+=1 else: poly+=1 elif x=="P": if y=="S": nike+=1 else: poly+=1 else: if y=="R": nike+=1 else: poly+=1 l+=1 r+=1 #print(nike,poly) nike=nike*(n//(len(a)*len(b))) poly=poly*(n//(len(a)*len(b))) rem=n%(len(a)*len(b)) l,r=0,0 for i in range(rem): x=a[l%(len(a))] y=b[r%(len(b))] if x==y: l+=1 r+=1 continue else: if x=="R": if y=="P": nike+=1 else: poly+=1 elif x=="P": if y=="S": nike+=1 else: poly+=1 else: if y=="R": nike+=1 else: poly+=1 l+=1 r+=1 print(nike,poly) ``` Yes
19,700
[ 0.282470703125, 0.130859375, 0.2147216796875, 0.2030029296875, -0.572265625, -0.316650390625, -0.311767578125, 0.0648193359375, 0.05914306640625, 0.63916015625, 0.87353515625, -0.07330322265625, 0.336669921875, -0.27001953125, -0.436767578125, -0.1778564453125, -0.85498046875, -0.7...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Submitted Solution: ``` def gcd(a, b): if b == 0: return a return gcd(b, a % b) def counter(s, t, r): p, q = 0, 0 for i in range(r): if s[i % k] == 'P': if t[i % m] == 'S': q += 1 elif t[i % m] == 'R': p += 1 elif s[i % k] == 'R': if t[i % m] == 'S': p += 1 elif t[i % m] == 'P': q += 1 else: if t[i % m] == 'P': p += 1 elif t[i % m] == 'R': q += 1 return p, q n = int(input()) s = input() t = input() k, m = len(s), len(t) r = k * m // gcd(k, m) p, q = counter(s, t, n // r) p1, q1 = counter(s, t, n % r) print(q + q1, p + p1) ``` No
19,701
[ 0.282470703125, 0.130859375, 0.2147216796875, 0.2030029296875, -0.572265625, -0.316650390625, -0.311767578125, 0.0648193359375, 0.05914306640625, 0.63916015625, 0.87353515625, -0.07330322265625, 0.336669921875, -0.27001953125, -0.436767578125, -0.1778564453125, -0.85498046875, -0.7...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Submitted Solution: ``` n=int(input()) aa,bb=0,0 a=list(input()) b=list(input()) rp=[] i=0 while( 1 ): if a[i%len(a)]=="R": if b[i%len(b)]=="P": bb+=1 elif b[i%len(b)]=="S": aa+=1 elif a[i%len(a)]=="P": if b[i%len(b)]=="R": aa+=1 elif b[i%len(b)]=="S": bb+=1 else: if b[i%len(b)]=="R": bb+=1 elif b[i%len(b)]=="P": aa+=1 i+=1 if ( i%len(a)==0 and i%len(b)==0 ) or i>n: break else: rp.append( (bb,aa) ) if len(rp)==n: print(bb,aa) else: w = n//len(rp) ww = n%len(rp) print( bb*w+rp[ww-1][0], aa*w+rp[ww-1][1] ) ``` No
19,702
[ 0.282470703125, 0.130859375, 0.2147216796875, 0.2030029296875, -0.572265625, -0.316650390625, -0.311767578125, 0.0648193359375, 0.05914306640625, 0.63916015625, 0.87353515625, -0.07330322265625, 0.336669921875, -0.27001953125, -0.436767578125, -0.1778564453125, -0.85498046875, -0.7...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Submitted Solution: ``` import sys def Solution(): s_A=list(map(str, sys.stdin.readline())) s_B=list(map(str, sys.stdin.readline())) zipped=list(zip(s_A, s_B)) Nikephoros=0 Polycarpus=0 for i in range (0, len(zipped)): if zipped[i][0]==zipped[i][1]: pass elif (zipped[i][0]=="S" and zipped[i][1]=="P") or \ (zipped[i][0]=="R" and zipped[i][1]=="S") or \ (zipped[i][0]=="P" and zipped[i][1]=="R"): Nikephoros+=1 else: Polycarpus+=1 print (Polycarpus, Nikephoros) Solution() ``` No
19,703
[ 0.282470703125, 0.130859375, 0.2147216796875, 0.2030029296875, -0.572265625, -0.316650390625, -0.311767578125, 0.0648193359375, 0.05914306640625, 0.63916015625, 0.87353515625, -0.07330322265625, 0.336669921875, -0.27001953125, -0.436767578125, -0.1778564453125, -0.85498046875, -0.7...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw. Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on. Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk). Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them. Input The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper. Output Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have. Examples Input 7 RPS RSPP Output 3 2 Input 5 RRRRRRRR R Output 0 0 Note In the first sample the game went like this: * R - R. Draw. * P - S. Nikephoros loses. * S - P. Polycarpus loses. * R - P. Nikephoros loses. * P - R. Polycarpus loses. * S - S. Draw. * R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. Submitted Solution: ``` n = int(input()) *N, = input() *P, = input() print(N,P) def is_greater(a, b): if (a == 'R' and b == 'S') or (a == 'P' and b == 'R') or (a == 'S' and b == 'P'): print('a>b') return 0 elif a == b: print('a=b') return 1 elif (b == 'R' and a == 'S') or (b == 'P' and a == 'R') or (b == 'S' and a == 'P'): print('a<b') return 2 return 'hurrah' loseN, loseP, lenN, lenP = 0, 0, len(N), len(P) for i in range(n): if is_greater( N[i%lenN], P[i%lenP] ) == 0: loseP += 1 elif is_greater( N[i%lenN], P[i%lenP] ) == 2: loseN += 1 print(loseN, loseP) ``` No
19,704
[ 0.282470703125, 0.130859375, 0.2147216796875, 0.2030029296875, -0.572265625, -0.316650390625, -0.311767578125, 0.0648193359375, 0.05914306640625, 0.63916015625, 0.87353515625, -0.07330322265625, 0.336669921875, -0.27001953125, -0.436767578125, -0.1778564453125, -0.85498046875, -0.7...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Tags: implementation Correct Solution: ``` q=int(input()) o,x,y=input().split() x=int(x) y=int(y) arz=min(x,y) tool=max(x,y) ans="" for i in range(1,q): o,x,y=input().split() x=int(x) y=int(y) if x>y: x,y=y,x if o=="+": if x>arz: arz=x if y>tool: tool=y else: if x<arz or y<tool: ans+="NO\n" else: ans+="YES\n" print(ans) ```
20,318
[ 0.32470703125, 0.1182861328125, 0.298095703125, 0.035888671875, -0.331298828125, 0.055419921875, 0.07086181640625, 0.282958984375, 0.2208251953125, 0.86279296875, 1.1318359375, -0.01238250732421875, 0.348388671875, -0.6064453125, -0.71044921875, 0.54345703125, -0.62646484375, -0.71...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Tags: implementation Correct Solution: ``` import sys MOD = 10**9 + 7 I = lambda:list(map(int,input().split())) from math import * from time import time from io import StringIO as stream from atexit import register def sync_with_stdio(sync=True): global input, flush if sync: flush = sys.stdout.flush else: sys.stdin = stream(sys.stdin.read()) input = lambda: sys.stdin.readline().rstrip('\r\n') #sys.stdout = stream() #register(lambda: sys.__stdout__.write(sys.stdout.getvalue())) sync_with_stdio(False) #input = sys.stdin.readline #print = sys.stdout.write n, = I() w = 0 h = 0 while n: n -= 1 c, x, y = input().split() x = int(x) y = int(y) if c == '+': if y > x: x, y = y , x w = max(w, x) h = max(h, y) else: if (x >= w and y >= h) or (y >= w and x >= h): print('YES') else: print('NO') ```
20,319
[ 0.32470703125, 0.1182861328125, 0.298095703125, 0.035888671875, -0.331298828125, 0.055419921875, 0.07086181640625, 0.282958984375, 0.2208251953125, 0.86279296875, 1.1318359375, -0.01238250732421875, 0.348388671875, -0.6064453125, -0.71044921875, 0.54345703125, -0.62646484375, -0.71...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Tags: implementation Correct Solution: ``` def sync_with_stdio(): import sys from io import StringIO as stream from atexit import register global input sys.stdin = stream(sys.stdin.read()) input = lambda: sys.stdin.readline().rstrip('\r\n') sys.stdout = stream() register(lambda: sys.__stdout__.write(sys.stdout.getvalue())) sync_with_stdio() MOD = 10**9 + 7 I = lambda:list(map(int,input().split())) n, = I() w = 0 h = 0 while n: n -= 1 c, x, y = input().split() x = int(x) y = int(y) if c == '+': if y > x: x, y = y , x w = max(w, x) h = max(h, y) else: if (x >= w and y >= h) or (y >= w and x >= h): print('YES') else: print('NO') ```
20,320
[ 0.32470703125, 0.1182861328125, 0.298095703125, 0.035888671875, -0.331298828125, 0.055419921875, 0.07086181640625, 0.282958984375, 0.2208251953125, 0.86279296875, 1.1318359375, -0.01238250732421875, 0.348388671875, -0.6064453125, -0.71044921875, 0.54345703125, -0.62646484375, -0.71...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Tags: implementation Correct Solution: ``` import sys lax = -10**9;lay = -10**9 for _ in range(int(input())) : sign,x,y = map(str,sys.stdin.readline().split()) x=int(x) y=int(y) if sign=="+" : if y > x : t=x x=y y=t lax = max(x,lax) lay = max(y,lay) else : if y > x : t=x x=y y=t #print(lax,lay) if lax<=x and lay<=y : print("YES") else : print("NO") ```
20,321
[ 0.32470703125, 0.1182861328125, 0.298095703125, 0.035888671875, -0.331298828125, 0.055419921875, 0.07086181640625, 0.282958984375, 0.2208251953125, 0.86279296875, 1.1318359375, -0.01238250732421875, 0.348388671875, -0.6064453125, -0.71044921875, 0.54345703125, -0.62646484375, -0.71...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Tags: implementation Correct Solution: ``` n = input() max_x = None max_y = None arr = [] inputs = [] for i in range(int(n)): _input = input() inputs.append(_input) for _input in inputs: _input = _input.split(' ') if _input[0] == '+': x = int(_input[1]) y = int(_input[2]) if x < y: temp = x x = y y = temp if max_x is None or max_x < x: max_x = x if max_y is None or max_y < y: max_y = y if _input[0] == '?': w = int(_input[1]) h = int(_input[2]) if w < h: temp = w w = h h = temp if max_x <= w and max_y <= h: arr.append(f'YES') else: arr.append(f'NO') for i in arr: print(i) ```
20,322
[ 0.32470703125, 0.1182861328125, 0.298095703125, 0.035888671875, -0.331298828125, 0.055419921875, 0.07086181640625, 0.282958984375, 0.2208251953125, 0.86279296875, 1.1318359375, -0.01238250732421875, 0.348388671875, -0.6064453125, -0.71044921875, 0.54345703125, -0.62646484375, -0.71...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Tags: implementation Correct Solution: ``` x,y = 0,0 res = '' n = int(input()) for _ in range(n): q = [i for i in input().split()] q[1] = int(q[1]) q[2] = int(q[2]) if q[0] == '+': x = max(x, min(q[1], q[2])) y = max(y, max(q[1], q[2])) elif x <= min(q[1], q[2]) and y <= max(q[1], q[2]): res += 'YES\n' else: res += 'NO\n' print(res) ```
20,323
[ 0.32470703125, 0.1182861328125, 0.298095703125, 0.035888671875, -0.331298828125, 0.055419921875, 0.07086181640625, 0.282958984375, 0.2208251953125, 0.86279296875, 1.1318359375, -0.01238250732421875, 0.348388671875, -0.6064453125, -0.71044921875, 0.54345703125, -0.62646484375, -0.71...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Tags: implementation Correct Solution: ``` import io, os input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline maxw, maxh = 0,0 for _ in range(int(input())): x = input().split() w, h = map(int, x[1:]) if h > w: w,h = h,w if x[0] == '+': if w > maxw: maxw = w if h > maxh: maxh = h else: print("YES" if maxw <= w and maxh <= h else "NO") ```
20,324
[ 0.32470703125, 0.1182861328125, 0.298095703125, 0.035888671875, -0.331298828125, 0.055419921875, 0.07086181640625, 0.282958984375, 0.2208251953125, 0.86279296875, 1.1318359375, -0.01238250732421875, 0.348388671875, -0.6064453125, -0.71044921875, 0.54345703125, -0.62646484375, -0.71...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Tags: implementation Correct Solution: ``` a=b=0 s='' for f in range(int(input())): i=input().split() x=min(int(i[1]),int(i[2])) y=max(int(i[1]),int(i[2])) if i[0]=='?': if x<a or y<b:s+='NO\n' else:s+='YES\n' else: a,b=max(a,x),max(b,y) print(s[:-1]) ```
20,325
[ 0.32470703125, 0.1182861328125, 0.298095703125, 0.035888671875, -0.331298828125, 0.055419921875, 0.07086181640625, 0.282958984375, 0.2208251953125, 0.86279296875, 1.1318359375, -0.01238250732421875, 0.348388671875, -0.6064453125, -0.71044921875, 0.54345703125, -0.62646484375, -0.71...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Submitted Solution: ``` import sys input = sys.stdin.readline n = int(input()) a = [list(map(str,input().split())) for _ in range(n)] tate = 0 yoko = 0 for i in range(n): if a[i][0] == "+": b = [int(a[i][1]),int(a[i][2])] b.sort() if tate < b[0]: tate = b[0] if yoko < b[1]: yoko = b[1] elif a[i][0] == "?": b = [int(a[i][1]),int(a[i][2])] b.sort() if tate <= b[0] and yoko <= b[1]: print("YES") else: print("NO") ``` Yes
20,326
[ 0.42578125, 0.1943359375, 0.3359375, -0.02294921875, -0.40478515625, 0.11669921875, -0.10107421875, 0.2724609375, 0.1451416015625, 0.89697265625, 1.02734375, 0.0036869049072265625, 0.3056640625, -0.59716796875, -0.7119140625, 0.51220703125, -0.5302734375, -0.71240234375, -0.54736...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Submitted Solution: ``` num = int(input()) log = [] for x in range(num): log.append(input().split()) a = 0 b = min(int(log[0][2]),int(log[0][1])) for y in log: first = int(y[1]) second = int(y[2]) if y[0] == '+': a = max(first,second,a) temp = min(first,second) b = max(temp,b) continue else: if (first < a or second < b) and (first < b or second < a): print('NO') else: print('Yes') ``` Yes
20,327
[ 0.42578125, 0.1943359375, 0.3359375, -0.02294921875, -0.40478515625, 0.11669921875, -0.10107421875, 0.2724609375, 0.1451416015625, 0.89697265625, 1.02734375, 0.0036869049072265625, 0.3056640625, -0.59716796875, -0.7119140625, 0.51220703125, -0.5302734375, -0.71240234375, -0.54736...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Submitted Solution: ``` n=int(input()) s='' maxx=0 maxy=0 for item in range(n): flag=input().split() a=int(flag[1]) b=int(flag[2]) if a>b: a,b=b,a if flag[0]=='+': if a>maxx: maxx=a if b>maxy: maxy=b else: if maxx<=a and maxy<=b: s+='YES\n' else: s+='NO\n' print(s) ``` Yes
20,328
[ 0.42578125, 0.1943359375, 0.3359375, -0.02294921875, -0.40478515625, 0.11669921875, -0.10107421875, 0.2724609375, 0.1451416015625, 0.89697265625, 1.02734375, 0.0036869049072265625, 0.3056640625, -0.59716796875, -0.7119140625, 0.51220703125, -0.5302734375, -0.71240234375, -0.54736...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Submitted Solution: ``` import sys import bisect input=sys.stdin.readline #t=int(input()) t=1 mod=10**9+7 for _ in range(t): n=int(input()) #l,r,d=map(int,input().split()) #s=input() #l=list(map(int,input().split())) l=[] for i in range(n): x=input() if x[0]=='+': x=list(map(int,x[2:].split())) if len(l)==0: l.append([[x[0],x[1]],[x[1],x[0]]]) else: l1=[] maxi=max(l[-1][0][0],l[-1][1][0],max(x[0],x[1])) mini=min(x[0],x[1]) mini=max(min(l[-1][0][0],l[-1][1][0]),mini) l.append([[maxi,mini],[mini,maxi]]) else: #print(l[-1]) x=list(map(int,x[2:].split())) if (l[-1][0][0]<=x[0] and l[-1][0][1]<=x[1]) : print("YES") elif l[-1][1][0]<=x[0] and l[-1][1][1]<=x[1] : print("YES") else: print("NO") ``` Yes
20,329
[ 0.42578125, 0.1943359375, 0.3359375, -0.02294921875, -0.40478515625, 0.11669921875, -0.10107421875, 0.2724609375, 0.1451416015625, 0.89697265625, 1.02734375, 0.0036869049072265625, 0.3056640625, -0.59716796875, -0.7119140625, 0.51220703125, -0.5302734375, -0.71240234375, -0.54736...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Submitted Solution: ``` n = int(input()) a = [] prov = [] prov_const = -1 def check(ci , cj , m): result = True for i in range(m): if ((ci >= a[i][0]) and (cj >= a[i][1] )) or ((ci >= a[i][1]) and (cj >= a[i][0])): continue else: result = False break return result for i in range(n): s = [i for i in input().split()] if s[0] == '+': a.append([int(s[1]) , int(s[2])]) if s[0] == '?': if prov_const >=0: if (int(s[1])>=prov[prov_const][0] and int(s[2]) >= prov[prov_const][1]) or (int(s[2])>=prov[prov_const][0] and int(s[1]) >= prov[prov_const][1]) and prov[prov_const][2] == True: print('YES') l = True elif (int(s[1])<=prov[prov_const][0] and int(s[2]) <= prov[prov_const][1]) and prov[prov_const][2] == False: print('NO') l = False else: l = check(int(s[1]) , int(s[2]) , len(a)) if l: print('YES') else: print('NO') else: l = check(int(s[1]), int(s[2]), len(a)) if l: print('YES') else: print('NO') prov.append([int(s[1]) , int(s[2]) , l]) prov_const +=1 ``` No
20,330
[ 0.42578125, 0.1943359375, 0.3359375, -0.02294921875, -0.40478515625, 0.11669921875, -0.10107421875, 0.2724609375, 0.1451416015625, 0.89697265625, 1.02734375, 0.0036869049072265625, 0.3056640625, -0.59716796875, -0.7119140625, 0.51220703125, -0.5302734375, -0.71240234375, -0.54736...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Submitted Solution: ``` from sys import stdin , stdout n = int(stdin.readline()) maxix , maxiy = 0 , 0 for _ in range(n): s = [x for x in stdin.readline().split()] s[1] , s[2] = max(s[1], s[2]) , min(s[1], s[2]) if s[0]=="+": maxix = max(maxix, int(s[1])) maxiy = max(maxiy, int(s[2])) else: ans='NO' h , w = int(s[1]) , int(s[2]) if (maxix <= h and maxiy <=w): ans='YES' stdout.write(ans + "\n") ``` No
20,331
[ 0.42578125, 0.1943359375, 0.3359375, -0.02294921875, -0.40478515625, 0.11669921875, -0.10107421875, 0.2724609375, 0.1451416015625, 0.89697265625, 1.02734375, 0.0036869049072265625, 0.3056640625, -0.59716796875, -0.7119140625, 0.51220703125, -0.5302734375, -0.71240234375, -0.54736...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Submitted Solution: ``` n = int(input()) stx = 0 sty = 0 for i in range(n): t, x, y = input().split() x = int(x) y = int(y) if x > y: x,y=y,x if t == '+': stx = max(stx, x) sty = max(sty, y) else: print('YNeos'[x >= stx and y >= sty::2]) ``` No
20,332
[ 0.42578125, 0.1943359375, 0.3359375, -0.02294921875, -0.40478515625, 0.11669921875, -0.10107421875, 0.2724609375, 0.1451416015625, 0.89697265625, 1.02734375, 0.0036869049072265625, 0.3056640625, -0.59716796875, -0.7119140625, 0.51220703125, -0.5302734375, -0.71240234375, -0.54736...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill x Γ— y fits into some wallet h Γ— w if either x ≀ h and y ≀ w or y ≀ h and x ≀ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: 1. +~x~y β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Input The first line contains a single integer n (2 ≀ n ≀ 5 β‹… 10^5) β€” the number of queries. Each of the next n lines contains a query of one of these two types: 1. +~x~y (1 ≀ x, y ≀ 10^9) β€” Polycarp earns a bill of size x Γ— y; 2. ?~h~w (1 ≀ h, w ≀ 10^9) β€” Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ— w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data. Output For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. Example Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO Note The queries of type 2 of the example: 1. Neither bill fits; 2. Both bills fit (just checking that you got that bills can overlap); 3. Both bills fit (both bills are actually the same); 4. All bills fit (too much of free space in a wallet is not a problem); 5. Only bill 1 Γ— 5 fit (all the others don't, thus it's "NO"). Submitted Solution: ``` def f(): x = int(input()) ;final = list(); one = list(); two = list() for a in range(x): string = list(map(str,input().split())) ch = string[0]; a = int(string[1]); b= int(string[2]) if ch == "+": one += [a] two += [b] final += [a,b] if ch == "?": if a in one and b in two: one.remove(a) two.remove(b) min_one = max(one) min_two = max(two) if a >= min_one and b >= min_two: print("YES") elif b>= min_one and a >= min_two: print("YES") else: print("NO") one += [a] two += [b] f() ``` No
20,333
[ 0.42578125, 0.1943359375, 0.3359375, -0.02294921875, -0.40478515625, 0.11669921875, -0.10107421875, 0.2724609375, 0.1451416015625, 0.89697265625, 1.02734375, 0.0036869049072265625, 0.3056640625, -0.59716796875, -0.7119140625, 0.51220703125, -0.5302734375, -0.71240234375, -0.54736...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Tags: binary search, data structures, greedy, implementation, math, sortings Correct Solution: ``` import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #from bisect import bisect_left as bl, bisect_right as br, insort #from heapq import heapify, heappush, heappop #from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(): return sys.stdin.buffer.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') #sys.setrecursionlimit(100000) #INF = float('inf') mod = int(1e9)+7 #from decimal import Decimal class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def fix(): global sumL, cntL, sumDouble while len(Double)<cntL: temp=LF[-1] Double.add(temp) LF.remove(temp) sumDouble+=temp while len(Double)>cntL: temp=Double[0] Double.remove(temp) LF.add(temp) sumDouble-=temp while Double and LF and Double[0]<LF[-1]: temp1,temp2=Double[0],LF[-1] LF.remove(temp2) Double.remove(temp1) LF.add(temp1) Double.add(temp2) sumDouble+=temp2-temp1 if sumDouble==sumL and cntL: temp1=Double[0] Double.remove(temp1) if LF: temp2=LF[-1] LF.remove(temp2) Double.add(temp2) sumDouble+=temp2 LF.add(temp1) sumDouble-=temp1 def add(tp,d): global sumF,sumL, sumDouble, cntL if not tp: sumF+=d else: sumL+=d cntL+=1 LF.add(d) def remove(tp,d): global sumF, sumL, sumDouble, cntL if not tp: sumF-=d else: sumL-=d cntL-=1 if d in LF: LF.remove(d) else: Double.remove(d) sumDouble-=d n=int(data()) sumL,sumF,sumDouble,cntL=0,0,0,0 LF=SortedList() Double=SortedList() for _ in range(n): tp,d=mdata() if d<0: remove(tp,-d) else: add(tp,d) fix() print(sumDouble+sumL+sumF) ```
20,452
[ -0.1513671875, -0.0176849365234375, 0.3466796875, 0.1859130859375, -0.400634765625, -0.6318359375, -0.1566162109375, 0.25341796875, -0.153076171875, 0.78076171875, 0.98583984375, 0.11322021484375, 0.5595703125, -0.8603515625, -0.4599609375, 0.05767822265625, -0.9580078125, -0.37939...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Tags: binary search, data structures, greedy, implementation, 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() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) # import heapq as hq # import bisect as bs # from collections import deque as dq # from collections import defaultdict as dc # from math import ceil,floor,sqrt # from collections import Counter spell = SortedList([0]) lightning = SortedList() s,k = 0,-1 for _ in range(N()): t,power = RL() s+=power if t==1: if lightning: spell.add(lightning[0]) if lightning[0]>spell[k]: s+=lightning[0]-spell[k] if power>0: lightning.add(power) spell.add(power) if power>spell[k]: s+=power-spell[k] else: lightning.discard(-power) if -power>spell[k]: s-=-power-spell[k] spell.discard(-power) if lightning: if lightning[0]>spell[k]: s-=lightning[0]-spell[k] spell.discard(lightning[0]) else: if power>0: spell.add(power) if power>spell[k]: s+=power-spell[k] else: if -power>spell[k]: s-=-power-spell[k] spell.discard(-power) k = max(k,-len(spell)) if -k>len(lightning)+1: k+=1 s-=spell[k] elif -k<len(lightning)+1 and spell[k]>0: s+=spell[k] k-=1 # print(spell,lightning,k,s) print(s) ```
20,453
[ -0.1513671875, -0.0176849365234375, 0.3466796875, 0.1859130859375, -0.400634765625, -0.6318359375, -0.1566162109375, 0.25341796875, -0.153076171875, 0.78076171875, 0.98583984375, 0.11322021484375, 0.5595703125, -0.8603515625, -0.4599609375, 0.05767822265625, -0.9580078125, -0.37939...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Tags: binary search, data structures, greedy, implementation, math, sortings Correct Solution: ``` from sys import stdin, stdout # 1 5 # 0 10 # 1 -5 # 0 5 # 1 11 # 0 -10 # # (5) => 5 # (5) 10 => 5 + 2*10 # 10 => 10 # 10 5 => 15 # 10 5 (11) => 11 + 2*10 + 5 = 36 # 5 (11) => 11 + 2*5 = 21 # 1-11 (sum, cnt) # 1-5 6-11 # 1-2 2-5 6-8 9-11 # class seg_node: def __init__(self, l, r, c, v): self.l = l self.r = r self.c = c self.v = v self.ln = None self.rn = None def seg_update(self, i, c, v): if self.l == self.r: self.c += c self.v += v return m = (self.l + self.r) // 2 if i <= m: if not self.ln: self.ln = seg_node(self.l, m, 0, 0) self.ln.seg_update(i, c, v) else: if not self.rn: self.rn = seg_node(m+1, self.r, 0, 0) self.rn.seg_update(i, c, v) self.c += c self.v += v def seg_query_r(self, cnt): if self.l == self.r: if cnt >= self.c: return [self.c, self.v] else: return [cnt, self.v * cnt // self.c] if self.c <= cnt: return [self.c, self.v] r_a = [0, 0] if self.rn: r_a = self.rn.seg_query_r(cnt) #print('cnt ' + str(cnt)) #print('l ' + str(self.l)) #print('r ' + str(self.r)) #print(r_a) #print('~~~~~~~~~~') if r_a[0] >= cnt: return r_a l_a = [0, 0] if self.ln: l_a = self.ln.seg_query_r(cnt - r_a[0]) res = [r_a[0] + l_a[0], r_a[1] + l_a[1]] #print(r_a) #print(l_a) #print(res) return res class seg_minnode: def __init__(self, l, r): self.l = l self.r = r self.c = 0 self.v = 10**10 self.ln = None self.rn = None def seg_update(self, i, c, v): if self.l == self.r: self.c += c self.v = v if self.c > 0 else 10**10 return self.v m = (self.l + self.r) // 2 lv = 10**10 if not self.ln else self.ln.v rv = 10**10 if not self.rn else self.rn.v if i <= m: if not self.ln: self.ln = seg_minnode(self.l, m) lv = self.ln.seg_update(i, c, v) else: if not self.rn: self.rn = seg_minnode(m + 1, self.r) rv = self.rn.seg_update(i, c, v) self.v = min(lv, rv) return self.v def seg_query(self): return self.v def two_types_of_spells(n, s, tpd_a): # 5, 10, 15 => 0, 1, 2 dic = {} ls = list(s) ls.sort() for i in range(len(ls)): dic[ls[i]] = i #print(dic) seg_root = seg_node(0, len(ls)-1, 0, 0) seg_minroot = seg_minnode(0, len(ls)-1) rsum = 0 lcnt = 0 ans = [] for tpd in tpd_a: i = dic[abs(tpd[1])] c = 1 if tpd[1] > 0 else -1 v = tpd[1] #print(i) #print(c) #print(v) rsum += tpd[1] #print(rsum) if tpd[0] == 1: if tpd[1] > 0: lcnt += 1 else: lcnt -= 1 i = dic[abs(tpd[1])] c = 1 if tpd[1] > 0 else -1 seg_minroot.seg_update(i, c, abs(v)) #print(c) #print(seg_minroot.v) seg_root.seg_update(i, c, v) #print(seg_root.l) #print(seg_root.r) #print(seg_root.c) #print(seg_root.v) if lcnt < 1: ans.append(rsum) continue # remove minimum lighting minV = seg_minroot.seg_query() #print(minV) seg_root.seg_update(dic[minV], -1, -minV) #print(seg_root.c) #print(seg_root.v) cnt, v = seg_root.seg_query_r(lcnt) # add minimum lighting seg_root.seg_update(dic[minV], 1, minV) ans.append(rsum + v) #print(v) #print('-----------') return ans n = int(stdin.readline()) tpd_a = [] s = set() for _ in range(n): tp, d = map(int, stdin.readline().split()) tpd_a.append([tp, d]) s.add(abs(d)) ans = two_types_of_spells(n, s, tpd_a) for a in ans: stdout.write(str(a) + '\n') ```
20,454
[ -0.1513671875, -0.0176849365234375, 0.3466796875, 0.1859130859375, -0.400634765625, -0.6318359375, -0.1566162109375, 0.25341796875, -0.153076171875, 0.78076171875, 0.98583984375, 0.11322021484375, 0.5595703125, -0.8603515625, -0.4599609375, 0.05767822265625, -0.9580078125, -0.37939...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Tags: binary search, data structures, greedy, implementation, math, sortings Correct Solution: ``` import io import os from collections import Counter, defaultdict, deque # Based on https://raw.githubusercontent.com/cheran-senthil/PyRival/master/pyrival/data_structures/SortedList.py # Modified to do range sum queries class SortedListWithSum: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._sum = sum(values) self._load = _load self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)] self._mins = [_list[0] for _list in _lists] self._list_lens = [len(_list) for _list in _lists] self._fen_tree = [] self._list_sums = [sum(_list) for _list in _lists] self._fen_tree_sum = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._fen_tree_sum[:] = self._list_sums _fen_tree_sum = self._fen_tree_sum for i in range(len(_fen_tree_sum)): if i | i + 1 < len(_fen_tree_sum): _fen_tree_sum[i | i + 1] += _fen_tree_sum[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_update_sum(self, index, value): """Update `fen_tree2[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree_sum while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_query_sum(self, end): """Return `sum(_fen_tree_sum[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree_sum x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens _list_sums = self._list_sums value = _lists[pos][idx] self._len -= 1 self._sum -= value self._fen_update(pos, -1) self._fen_update_sum(pos, -value) del _lists[pos][idx] _list_lens[pos] -= 1 _list_sums[pos] -= value if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _list_sums[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens _list_sums = self._list_sums self._len += 1 self._sum += value if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) self._fen_update_sum(pos, value) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _list_sums[pos] += value _mins[pos] = _list[0] if _load + _load < len(_list): back = _list[_load:] old_len = _list_lens[pos] old_sum = _list_sums[pos] new_len_front = _load new_len_back = old_len - new_len_front new_sum_back = sum(back) new_sum_front = old_sum - new_sum_back _lists.insert(pos + 1, back) _list_lens.insert(pos + 1, new_len_back) _list_sums.insert(pos + 1, new_sum_back) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = new_len_front _list_sums[pos] = new_sum_front del _list[_load:] # assert len(_lists[pos]) == _list_lens[pos] # assert len(_lists[pos + 1]) == _list_lens[pos + 1] # assert sum(_lists[pos]) == _list_sums[pos] # assert sum(_lists[pos + 1]) == _list_sums[pos + 1] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) _list_sums.append(value) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError("{0!r} not in list".format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return "SortedList({0})".format(list(self)) def query(self, i, j): if i == j: return 0 pos1, idx1 = self._fen_findkth(self._len + i if i < 0 else i) pos2, idx2 = self._fen_findkth(self._len + j if j < 0 else j) return ( sum(self._lists[pos1][idx1:]) + (self._fen_query_sum(pos2) - self._fen_query_sum(pos1 + 1)) + sum(self._lists[pos2][:idx2]) ) def sum(self): return self._sum class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def solve(N, queries): L = SortedList() F = SortedList() sumL = 0 sumF = 0 # Stores best candidates for doubling which is everything except for the smallest lightning # Can only double at most len(L) spells cand = SortedListWithSum() # Store smallest lightning separately smallestL = None def add(d, tp): nonlocal sumL, sumF, smallestL toAdd = d if tp == 0: F.add(d) sumF += d else: if not L or L[0] > d: # adding new smallest lightning, bump old smallestL into candidate list toAdd = smallestL smallestL = d L.add(d) sumL += d if toAdd is not None: cand.add(toAdd) def remove(d, tp): nonlocal sumL, sumF, smallestL toRemove = d if tp == 0: F.remove(d) sumF -= d else: L.remove(d) sumL -= d smallestL = None if not L else L[0] if not L or smallestL > d: # removed old smallest lightning, pull new smallestL from candidate list toRemove = smallestL if toRemove is not None: cand.remove(toRemove) ans = [] for tp, d in queries: if d > 0: # learn add(d, tp) else: # unlearn remove(-d, tp) ans.append( cand.query(max(0, len(cand) - len(L)), len(cand)) + sumL + sumF ) return "\n".join(map(str, ans)) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline (N,) = [int(x) for x in input().split()] queries = ((int(x) for x in input().split()) for i in range(N)) ans = solve(N, queries) print(ans) ```
20,455
[ -0.1513671875, -0.0176849365234375, 0.3466796875, 0.1859130859375, -0.400634765625, -0.6318359375, -0.1566162109375, 0.25341796875, -0.153076171875, 0.78076171875, 0.98583984375, 0.11322021484375, 0.5595703125, -0.8603515625, -0.4599609375, 0.05767822265625, -0.9580078125, -0.37939...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Tags: binary search, data structures, greedy, implementation, math, sortings Correct Solution: ``` class BalancingTree: def __init__(self, n): self.N = n self.root = self.node(1<<n, 1<<n) def debug(self): def debug_info(nd_): return (nd_.value - 1, nd_.pivot , nd_.left.value - 1 if nd_.left else -1, nd_.right.value - 1 if nd_.right else -1,nd_.cnt) def debug_node(nd): re = [] if nd.left: re += debug_node(nd.left) if nd.value: re.append(debug_info(nd)) if nd.right: re += debug_node(nd.right) return re print("Debug - root =", self.root.value - 1, debug_node(self.root)[:50]) def append(self, v): v += 1 nd = self.root while True: if v == nd.value: return 0 else: nd.cnt+=1 nd.sum+=v-1 mi, ma = min(v, nd.value), max(v, nd.value) if mi < nd.pivot: nd.value = ma if nd.left: nd = nd.left v = mi else: p = nd.pivot nd.left = self.node(mi, p - (p&-p)//2) break else: nd.value = mi if nd.right: nd = nd.right v = ma else: p = nd.pivot nd.right = self.node(ma, p + (p&-p)//2) break def kth(self,k): cnt=k nd=self.root while True: if nd.left: if nd.left.cnt<k: k-=nd.left.cnt+1 if nd.right: nd=nd.right else: raise IndexError("BalancingTree doesn't hold kth number") elif nd.left.cnt==k: return nd.value-1 else: nd=nd.left else: if k==0: return nd.value-1 if nd.right: k-=1 nd=nd.right else: raise IndexError("BalancingTree doesn't hold kth number") def kth_sum(self,k): if k==-1: return 0 cnt=k res_sum=0 nd=self.root while True: if nd.left: if nd.left.cnt<k: k-=nd.left.cnt+1 res_sum+=nd.left.sum+nd.value-1 if nd.right: nd=nd.right else: raise IndexError("BalancingTree doesn't hold kth number") elif nd.left.cnt==k: res_sum+=nd.left.sum+nd.value-1 return res_sum else: nd=nd.left else: if k==0: return res_sum+nd.value-1 if nd.right: k-=1 res_sum+=nd.value-1 nd=nd.right else: print(cnt,self.size,nd.value-1,nd.right) self.debug() raise IndexError("BalancingTree doesn't hold kth number") def kth_sum_big(self,k): res_sum=self.sum if self.size>k: res_sum-=self.kth_sum(self.size-k-2) return res_sum else: raise IndexError("BalancingTree doesn't hold kth number") def leftmost(self, nd): if nd.left: return self.leftmost(nd.left) return nd def rightmost(self, nd): if nd.right: return self.rightmost(nd.right) return nd def find_l(self, v): v += 1 nd = self.root prev = 0 if nd.value < v: prev = nd.value while True: if v <= nd.value: if nd.left: nd = nd.left else: return prev - 1 else: prev = nd.value if nd.right: nd = nd.right else: return prev - 1 def find_r(self, v): v += 1 nd = self.root prev = 0 if nd.value > v: prev = nd.value while True: if v < nd.value: prev = nd.value if nd.left: nd = nd.left else: return prev - 1 else: if nd.right: nd = nd.right else: return prev - 1 @property def max(self): if self.size: return self.find_l((1<<self.N)-1) return 0 @property def min(self): if self.size: return self.find_r(-1) return 0 @property def sum(self): return self.root.sum-self.root.value+1 @property def size(self): return self.root.cnt-1 def delete(self, v, nd = None, prev = None): v += 1 if not nd: nd = self.root if not prev: prev = nd while v != nd.value: prev = nd nd.cnt-=1 nd.sum-=v-1 if v <= nd.value: if nd.left: nd = nd.left else: return else: if nd.right: nd = nd.right else: return nd.cnt-=1 nd.sum-=v-1 if (not nd.left) and (not nd.right): if not prev.left: prev.right=None elif not prev.right: prev.left=None else: if nd.pivot==prev.left.pivot: prev.left=None else: prev.right=None elif nd.right: nd.value = self.leftmost(nd.right).value self.delete(nd.value - 1, nd.right, nd) else: nd.value = self.rightmost(nd.left).value self.delete(nd.value - 1, nd.left, nd) def __contains__(self, v: int) -> bool: return self.find_r(v - 1) == v def __len__(self): return self.size class node: def __init__(self, v, p): self.value = v self.pivot = p self.left = None self.right = None self.cnt=1 self.sum=v-1 import sys input=sys.stdin.readline n=int(input()) xybst=BalancingTree(30) S=0 split_bst=[BalancingTree(30),BalancingTree(30)] for _ in range(n): t,d=map(int,input().split()) if d<0: split_bst[t].delete(abs(d)) xybst.delete(abs(d)) else: split_bst[t].append(abs(d)) xybst.append(abs(d)) S+=d x,y=len(split_bst[0]),len(split_bst[1]) tmp,tmpy=xybst.kth_sum_big(y-1),split_bst[1].kth_sum_big(y-1) if tmp==tmpy and y: print(S+tmp-split_bst[1].min+split_bst[0].max) else: print(S+tmp) ```
20,456
[ -0.1513671875, -0.0176849365234375, 0.3466796875, 0.1859130859375, -0.400634765625, -0.6318359375, -0.1566162109375, 0.25341796875, -0.153076171875, 0.78076171875, 0.98583984375, 0.11322021484375, 0.5595703125, -0.8603515625, -0.4599609375, 0.05767822265625, -0.9580078125, -0.37939...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Tags: binary search, data structures, greedy, implementation, 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() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) # import heapq as hq # import bisect as bs # from collections import deque as dq # from collections import defaultdict as dc # from math import ceil,floor,sqrt # from collections import Counter spell = SortedList([0]) lightning = SortedList() data = [map(int,line.split()) for line in sys.stdin.readlines()] n = data[0].__next__() s,k = 0,-1 for i in range(1,n+1): t,power = data[i] s+=power if t==1: if lightning: spell.add(lightning[0]) if lightning[0]>spell[k]: s+=lightning[0]-spell[k] if power>0: lightning.add(power) spell.add(power) if power>spell[k]: s+=power-spell[k] else: lightning.discard(-power) if -power>spell[k]: s-=-power-spell[k] spell.discard(-power) if lightning: if lightning[0]>spell[k]: s-=lightning[0]-spell[k] spell.discard(lightning[0]) else: if power>0: spell.add(power) if power>spell[k]: s+=power-spell[k] else: if -power>spell[k]: s-=-power-spell[k] spell.discard(-power) k = max(k,-len(spell)) if -k>len(lightning)+1: k+=1 s-=spell[k] elif -k<len(lightning)+1 and spell[k]>0: s+=spell[k] k-=1 # print(spell,lightning,k,s) print(s) ```
20,457
[ -0.1513671875, -0.0176849365234375, 0.3466796875, 0.1859130859375, -0.400634765625, -0.6318359375, -0.1566162109375, 0.25341796875, -0.153076171875, 0.78076171875, 0.98583984375, 0.11322021484375, 0.5595703125, -0.8603515625, -0.4599609375, 0.05767822265625, -0.9580078125, -0.37939...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Tags: binary search, data structures, greedy, implementation, math, sortings Correct Solution: ``` #!/usr/bin/env python3 import sys input = sys.stdin.readline class SegmentTree: def __init__(self, a): # Operator self.op = lambda a, b : a + b # Identity element self.e = 0 self.n = len(a) self.lv = (self.n - 1).bit_length() self.size = 2**self.lv self.data = [self.e] * (2*self.size - 1) # Bisect checking function self._check = lambda x, acc : acc >= x self._acc = self.e self.initialize(a) # Initialize data def initialize(self, a): for i in range(self.n): self.data[self.size + i - 1] = a[i] for i in range(self.size-2, -1, -1): self.data[i] = self.op(self.data[i*2 + 1], self.data[i*2 + 2]) # Update ak as x (0-indexed) def update(self, k, x): k += self.size - 1 self.data[k] = x while k > 0: k = (k - 1) // 2 self.data[k] = self.op(self.data[2*k+1], self.data[2*k+2]) # Min value in [l, r) (0-indexed) def fold(self, l, r): L = l + self.size; R = r + self.size s = self.e while L < R: if R & 1: R -= 1 s = self.op(s, self.data[R-1]) if L & 1: s = self.op(s, self.data[L-1]) L += 1 L >>= 1; R >>= 1 return s def _bisect_forward(self, x, start, k): # When segment-k is at the bottom, accumulate and return. if k >= self.size - 1: self._acc = self.op(self._acc, self.data[k]) if self._check(x, self._acc): return k - (self.size - 1) else: return -1 width = 2**(self.lv - (k+1).bit_length() + 1) mid = (k+1) * width + width // 2 - self.size # When left-child isn't in range, just look at right-child. if mid <= start: return self._bisect_forward(x, start, 2*k + 2) # When segment-k is in range and has no answer in it, accumulate and return -1 tmp_acc = self.op(self._acc, self.data[k]) if start <= mid - width // 2 and not self._check(x, tmp_acc): self._acc = tmp_acc return -1 # Check left-child then right-child vl = self._bisect_forward(x, start, 2*k + 1) if vl != -1: return vl return self._bisect_forward(x, start, 2*k + 2) # Returns min index s.t. start <= index and satisfy check(data[start:idx)) = True def bisect_forward(self, x, start=None): if start: ret = self._bisect_forward(x, start, 0) else: ret = self._bisect_forward(x, 0, 0) self._acc = self.e return ret def _bisect_backward(self, x, start, k): # When segment-k is at the bottom, accumulate and return. if k >= self.size - 1: self._acc = self.op(self._acc, self.data[k]) if self._check(x, self._acc): return k - (self.size - 1) else: return -1 width = 2**(self.lv - (k+1).bit_length() + 1) mid = (k+1) * width + width // 2 - self.size # When right-child isn't in range, just look at right-child. if mid >= start: return self._bisect_backward(x, start, 2*k + 1) # When segment-k is in range and has no answer in it, accumulate and return -1 tmp_acc = self.op(self._acc, self.data[k]) if start > mid + width // 2 and not self._check(x, tmp_acc): self._acc = tmp_acc return -1 # Check right-child then left-child vl = self._bisect_backward(x, start, 2*k + 2) if vl != -1: return vl return self._bisect_backward(x, start, 2*k + 1) # Returns max index s.t. index < start and satisfy check(data[idx:start)) = True def bisect_backward(self, x, start=None): if start: ret = self._bisect_backward(x, start, 0) else: ret = self._bisect_backward(x, self.n, 0) self._acc = self.e return ret n = int(input()) query = [] seen = set([0]) for _ in range(n): kind, val = map(int, input().split()) query.append((kind, val)) if val > 0: seen.add(val) unique = list(seen) unique.sort() comp = {val: i for i, val in enumerate(unique)} decomp = {i: val for i, val in enumerate(unique)} decopm = {} nn = len(comp) base = [0] * nn STfire = SegmentTree(base) STnum = SegmentTree(base) STval = SegmentTree(base) tnum = 0 fnum = 0 spell = 0 total = 0 for kind, val in query: cd = comp[abs(val)] if val > 0: STval.update(cd, val) STnum.update(cd, 1) total += val if kind == 1: tnum += 1 else: STfire.update(cd, 1) fnum += 1 else: total += val STval.update(cd, 0) STnum.update(cd, 0) if kind == 1: tnum -= 1 else: STfire.update(cd, 0) fnum -= 1 spell = tnum + fnum if fnum == 0: fid = -1 else: fid = STfire.bisect_forward(fnum) l = STnum.bisect_forward(spell - tnum) if tnum == 0: print(total) continue if fid >= l + 1: double_total = STval.fold(l + 1, nn) print(total + double_total) else: l = STnum.bisect_forward(spell - tnum + 1) double_total = STval.fold(l + 1, nn) if fnum > 0: print(total + double_total + decomp[fid]) else: print(total + double_total) ```
20,458
[ -0.1513671875, -0.0176849365234375, 0.3466796875, 0.1859130859375, -0.400634765625, -0.6318359375, -0.1566162109375, 0.25341796875, -0.153076171875, 0.78076171875, 0.98583984375, 0.11322021484375, 0.5595703125, -0.8603515625, -0.4599609375, 0.05767822265625, -0.9580078125, -0.37939...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Tags: binary search, data structures, greedy, implementation, math, sortings Correct Solution: ``` from math import inf, log2 class SegmentTree: def __init__(self, array, func=max): self.n = len(array) self.size = 2**(int(log2(self.n-1))+1) if self.n != 1 else 1 self.func = func self.default = 0 if self.func != min else inf self.data = [self.default] * (2 * self.size) self.process(array) def process(self, array): self.data[self.size : self.size+self.n] = array for i in range(self.size-1, -1, -1): self.data[i] = self.func(self.data[2*i], self.data[2*i+1]) def query(self, alpha, omega): """Returns the result of function over the range (inclusive)!""" if alpha == omega: return self.data[alpha + self.size] res = self.default alpha += self.size omega += self.size + 1 while alpha < omega: if alpha & 1: res = self.func(res, self.data[alpha]) alpha += 1 if omega & 1: omega -= 1 res = self.func(res, self.data[omega]) alpha >>= 1 omega >>= 1 return res def update(self, index, value): """Updates the element at index to given value!""" index += self.size self.data[index] = value index >>= 1 while index: self.data[index] = self.func(self.data[2*index], self.data[2*index+1]) index >>= 1 class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if not True else 1): n = int(input()) lightning, fire = 0, 0 slf = SortedList([]) sll = SortedList([]) sl = SortedList([]) queries = [] oof = [] for i in range(n): tp, d = map(int, input().split()) queries += [[tp, d]] oof += [abs(d)] oof = sorted(list(set(oof))) high = len(oof) + 10 st = SegmentTree([0]*high, func=lambda a,b:a+b) di = {} for i in range(len(oof)): di[oof[i]] = i for tp, d in queries: if not tp: # fire fire += d if d > 0: slf.add(d) sl.add(d) st.update(di[d], d) else: slf.remove(-d) sl.remove(-d) st.update(di[-d], 0) else: # lightning lightning += d if d > 0: sll.add(d) sl.add(d) st.update(di[d], d) else: sll.remove(-d) sl.remove(-d) st.update(di[-d], 0) if sll.__len__() == 0: print(fire + lightning) continue least = sl.__getitem__(sl.__len__() - sll.__len__()) if fire and slf.__getitem__(slf.__len__()-1) >= least: print(least + st.query(di[least]+1, high-1)*2 + st.query(0, di[least])) else: if fire: firemax = slf.__getitem__(slf.__len__()-1) print(least + st.query(di[least]+1, high-1)*2 + firemax*2 + st.query(0, di[firemax]-1)) else: print(least + st.query(di[least] + 1, high - 1) * 2) ```
20,459
[ -0.1513671875, -0.0176849365234375, 0.3466796875, 0.1859130859375, -0.400634765625, -0.6318359375, -0.1566162109375, 0.25341796875, -0.153076171875, 0.78076171875, 0.98583984375, 0.11322021484375, 0.5595703125, -0.8603515625, -0.4599609375, 0.05767822265625, -0.9580078125, -0.37939...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Submitted Solution: ``` import bisect import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline class TreeSet(object): """ Binary-tree set like java Treeset. Duplicate elements will not be added. When added new element, TreeSet will be sorted automatically. """ def __init__(self, elements): self._treeset = [] self.addAll(elements) def addAll(self, elements): for element in elements: if element in self: continue self.add(element) def add(self, element): if element not in self: bisect.insort(self._treeset, element) def ceiling(self, e): index = bisect.bisect_right(self._treeset, e) if self[index - 1] == e: return e return self._treeset[bisect.bisect_right(self._treeset, e)] def floor(self, e): index = bisect.bisect_left(self._treeset, e) if self[index] == e: return e else: return self._treeset[bisect.bisect_left(self._treeset, e) - 1] def __getitem__(self, num): return self._treeset[num] def __len__(self): return len(self._treeset) def clear(self): """ Delete all elements in TreeSet. """ self._treeset = [] def clone(self): """ Return shallow copy of self. """ return TreeSet(self._treeset) def remove(self, element): """ Remove element if element in TreeSet. """ try: self._treeset.remove(element) except ValueError: return False return True def __iter__(self): """ Do ascending iteration for TreeSet """ for element in self._treeset: yield element def pop(self, index): return self._treeset.pop(index) def __str__(self): return str(self._treeset) def __eq__(self, target): if isinstance(target, TreeSet): return self._treeset == target.treeset elif isinstance(target, list): return self._treeset == target def __contains__(self, e): """ Fast attribution judgment by bisect """ try: return e == self._treeset[bisect.bisect_left(self._treeset, e)] except: return False n = int(input()) MAX_VALUE = int(1e9+1) ts = TreeSet([-MAX_VALUE, MAX_VALUE]) info = {} cntL = 0 cntL2 = 0 min2 = MAX_VALUE sum1 = 0 sum2 = 0 for _ in range(n): type, power = list(map(int, input().split())) if power>0: ts.add(power) info[power] = type if min2 == ts[len(ts) - cntL-1]: sum1 += power if type == 1: cntL += 1 min2 = ts[len(ts) - cntL - 1] sum2 += min2 sum1 -= min2 cntL2 += info[min2] else: sum2 += power cntL2 += info[power] if type == 0: sum2 -= min2 sum1 += min2 cntL2 -= info.get(min2, 0) # min2 = ts[len(ts) - cntL - 1] else: cntL += 1 else: power = abs(power) ts.remove(power) if min2 == ts[len(ts) - cntL - 1]: sum1 -= power if type == 1: sum2 -= min2 sum1 += min2 cntL2 -= info.get(min2, 0) cntL -= 1 # min2 = ts[len(ts) - cntL - 1] else: sum2 -= power cntL2 -= info[power] if type == 0: min2 = ts[len(ts) - cntL - 1] sum2 += min2 sum1 -= min2 cntL2 += info[min2] else: cntL -= 1 min2 = ts[len(ts) - cntL - 1] if cntL2 < cntL or cntL == 0: ans = 2*sum2 + sum1 else: if len(ts) - cntL - 2 > 0: max1 = ts[len(ts) - cntL - 2] else: max1 = 0 ans = 2*sum2 - min2 + sum1 + max1 print(ans) ``` Yes
20,460
[ -0.02728271484375, 0.0516357421875, 0.274658203125, 0.2027587890625, -0.4013671875, -0.474853515625, -0.2130126953125, 0.25390625, -0.1314697265625, 0.7529296875, 0.90966796875, 0.1697998046875, 0.53271484375, -0.84521484375, -0.41748046875, 0.01776123046875, -0.8857421875, -0.3027...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Submitted Solution: ``` class BalancingTree: def __init__(self, n): self.N = n self.root = self.node(1<<n, 1<<n) def debug(self): def debug_info(nd_): return (nd_.value - 1, nd_.pivot , nd_.left.value - 1 if nd_.left else -1, nd_.right.value - 1 if nd_.right else -1,nd_.cnt) def debug_node(nd): re = [] if nd.left: re += debug_node(nd.left) if nd.value: re.append(debug_info(nd)) if nd.right: re += debug_node(nd.right) return re print("Debug - root =", self.root.value - 1, debug_node(self.root)[:50]) def append(self, v): v += 1 nd = self.root while True: if v == nd.value: return 0 else: nd.cnt+=1 nd.sum+=v-1 mi, ma = min(v, nd.value), max(v, nd.value) if mi < nd.pivot: nd.value = ma if nd.left: nd = nd.left v = mi else: p = nd.pivot nd.left = self.node(mi, p - (p&-p)//2) break else: nd.value = mi if nd.right: nd = nd.right v = ma else: p = nd.pivot nd.right = self.node(ma, p + (p&-p)//2) break def kth(self,k): cnt=k nd=self.root while True: if nd.left: if nd.left.cnt<k: k-=nd.left.cnt+1 if nd.right: nd=nd.right else: raise IndexError("BalancingTree doesn't hold kth number") elif nd.left.cnt==k: return nd.value-1 else: nd=nd.left else: if k==0: return nd.value-1 if nd.right: k-=1 nd=nd.right else: raise IndexError("BalancingTree doesn't hold kth number") def kth_sum(self,k): if k==-1: return 0 cnt=k res_sum=0 nd=self.root while True: if nd.left: if nd.left.cnt<k: k-=nd.left.cnt+1 res_sum+=nd.left.sum+nd.value-1 if nd.right: nd=nd.right else: raise IndexError("BalancingTree doesn't hold kth number") elif nd.left.cnt==k: res_sum+=nd.left.sum+nd.value-1 return res_sum else: nd=nd.left else: if k==0: return res_sum+nd.value-1 if nd.right: k-=1 res_sum+=nd.value-1 nd=nd.right else: print(cnt,self.size,nd.value-1,nd.right) self.debug() raise IndexError("BalancingTree doesn't hold kth number") def kth_sum_big(self,k): res_sum=self.sum if self.size>k: res_sum-=self.kth_sum(self.size-k-2) return res_sum else: raise IndexError("BalancingTree doesn't hold kth number") def leftmost(self, nd): if nd.left: return self.leftmost(nd.left) return nd def rightmost(self, nd): if nd.right: return self.rightmost(nd.right) return nd def find_l(self, v): v += 1 nd = self.root prev = 0 if nd.value < v: prev = nd.value while True: if v <= nd.value: if nd.left: nd = nd.left else: return prev - 1 else: prev = nd.value if nd.right: nd = nd.right else: return prev - 1 def find_r(self, v): v += 1 nd = self.root prev = 0 if nd.value > v: prev = nd.value while True: if v < nd.value: prev = nd.value if nd.left: nd = nd.left else: return prev - 1 else: if nd.right: nd = nd.right else: return prev - 1 @property def max(self): return self.find_l((1<<self.N)-1) @property def min(self): return self.find_r(-1) @property def sum(self): return self.root.sum-self.root.value+1 @property def size(self): return self.root.cnt-1 def delete(self, v, nd = None, prev = None): v += 1 if not nd: nd = self.root if not prev: prev = nd while v != nd.value: prev = nd nd.cnt-=1 nd.sum-=v-1 if v <= nd.value: if nd.left: nd = nd.left else: return else: if nd.right: nd = nd.right else: return nd.cnt-=1 nd.sum-=v-1 if (not nd.left) and (not nd.right): if not prev.left: prev.right=None elif not prev.right: prev.left=None else: if nd.pivot==prev.left.pivot: prev.left=None else: prev.right=None elif nd.right: nd.value = self.leftmost(nd.right).value self.delete(nd.value - 1, nd.right, nd) else: nd.value = self.rightmost(nd.left).value self.delete(nd.value - 1, nd.left, nd) def __contains__(self, v: int) -> bool: return self.find_r(v - 1) == v class node: def __init__(self, v, p): self.value = v self.pivot = p self.left = None self.right = None self.cnt=1 self.sum=v-1 import sys input=sys.stdin.readline n=int(input()) xybst=BalancingTree(30) xbst=BalancingTree(30) ybst=BalancingTree(30) x,y=0,0 S=0 for _ in range(n): t,d=map(int,input().split()) if d<0: if t==0: xbst.delete(abs(d)) x-=1 else: ybst.delete(abs(d)) y-=1 xybst.delete(abs(d)) else: if t==0: xbst.append(d) x+=1 else: ybst.append(d) y+=1 xybst.append(abs(d)) S+=d if x==0: if y==0: print(0) else: print(2*S-ybst.min) else: if y==0: print(S) else: tmp,tmpy=xybst.kth_sum_big(y-1),ybst.kth_sum_big(y-1) if tmp==tmpy: print(S+tmp-ybst.min+xbst.max) else: print(S+tmp) ``` Yes
20,461
[ -0.02728271484375, 0.0516357421875, 0.274658203125, 0.2027587890625, -0.4013671875, -0.474853515625, -0.2130126953125, 0.25390625, -0.1314697265625, 0.7529296875, 0.90966796875, 0.1697998046875, 0.53271484375, -0.84521484375, -0.41748046875, 0.01776123046875, -0.8857421875, -0.3027...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Submitted Solution: ``` import sys, math import io, os data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #from bisect import bisect_left as bl, bisect_right as br, insort #from heapq import heapify, heappush, heappop #from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations #def data(): return sys.stdin.buffer.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') #sys.setrecursionlimit(100000) #INF = float('inf') mod = int(1e9)+7 #from decimal import Decimal class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def fix(): global sumL, cntL, sumDouble while len(Double)<cntL: temp=LF[-1] Double.add(temp) LF.remove(temp) sumDouble+=temp while len(Double)>cntL: temp=Double[0] Double.remove(temp) LF.add(temp) sumDouble-=temp while Double and LF and Double[0]<LF[-1]: temp1,temp2=Double[0],LF[-1] LF.remove(temp2) Double.remove(temp1) LF.add(temp1) Double.add(temp2) sumDouble+=temp2-temp1 if sumDouble==sumL and cntL: temp1=Double[0] Double.remove(temp1) if LF: temp2=LF[-1] LF.remove(temp2) Double.add(temp2) sumDouble+=temp2 LF.add(temp1) sumDouble-=temp1 def add(tp,d): global sumF,sumL, sumDouble, cntL if not tp: sumF+=d else: sumL+=d cntL+=1 LF.add(d) def remove(tp,d): global sumF, sumL, sumDouble, cntL if not tp: sumF-=d else: sumL-=d cntL-=1 if d in LF: LF.remove(d) else: Double.remove(d) sumDouble-=d n=int(data()) sumL,sumF,sumDouble,cntL=0,0,0,0 LF=SortedList() Double=SortedList() for _ in range(n): tp,d=mdata() if d<0: remove(tp,-d) else: add(tp,d) fix() out(sumDouble+sumL+sumF) ``` Yes
20,462
[ -0.02728271484375, 0.0516357421875, 0.274658203125, 0.2027587890625, -0.4013671875, -0.474853515625, -0.2130126953125, 0.25390625, -0.1314697265625, 0.7529296875, 0.90966796875, 0.1697998046875, 0.53271484375, -0.84521484375, -0.41748046875, 0.01776123046875, -0.8857421875, -0.3027...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Submitted Solution: ``` import sys input = sys.stdin.buffer.readline class fenwick: def __init__(self, n): self.mem = [0]*(n+1) def get(self, u): return self.psum(u) - self.psum(u-1) def add(self, u, val): while u <= n: self.mem[u] += val u += (u & -u) def psum(self, u): sm = 0 while u > 0: sm += self.mem[u] u -= (u & -u) return sm def pos(self, val): l, r = 0, n+1 while l < r: m = (l+r)//2 if self.psum(m) < val: l = m+1 else: r = m return l n, q = int(input()), [] for _ in range(n): ligt, power = map(int, input().split()) q.append((power, ligt)) p2o = {} for i, (power, _) in enumerate(sorted(q, reverse=True)): if power > 0: p2o[power] = i+1 res, nspell, nfire = [], 0, 0 frcc, spcc, pwcc = fenwick(n), fenwick(n), fenwick(n) for power, ligt in q: nspell += 1 if power > 0 else -1 if not ligt: nfire += 1 if power > 0 else -1 nligt = nspell-nfire order = p2o[abs(power)] if not ligt: frcc.add(order, 1 if power > 0 else -1) spcc.add(order, 1 if power > 0 else -1) pwcc.add(order, power) sm = 0 if nfire == 0: sm = pwcc.psum(n) + pwcc.psum(spcc.pos(nligt-1)) elif nligt == 0: sm = pwcc.psum(n) else: p = spcc.pos(nligt) if frcc.psum(p): sm = pwcc.psum(n) + pwcc.psum(p) else: sm = pwcc.psum(n) + pwcc.psum(p-1) + pwcc.get(frcc.pos(1)) res.append(sm) print('\n'.join(map(str, res))) ``` Yes
20,463
[ -0.02728271484375, 0.0516357421875, 0.274658203125, 0.2027587890625, -0.4013671875, -0.474853515625, -0.2130126953125, 0.25390625, -0.1314697265625, 0.7529296875, 0.90966796875, 0.1697998046875, 0.53271484375, -0.84521484375, -0.41748046875, 0.01776123046875, -0.8857421875, -0.3027...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Submitted Solution: ``` x = {1:[],0:[]} for _ in range(int(input())): tp, d = map(int,input().split()) if d<0: x[tp] = list(filter(lambda a: a!=(-1*d), x[tp])) else: x[tp].append(d) if len(x[1]) == 0: print(sum(x[0])) elif len(x[1]) == 1: if len(x[0])==0: print(x[1][0]) elif len(x[0])==1: print(x[1][0] + 2*x[0][0]) else: x[0].sort(reverse=True) print(x[1][0] + 2*x[0][0] + sum(x[0][1:len(x[0])])) else: x[0].sort(reverse = True) x[1].sort() if len(x[0])==0: print(x[1][0]+ 2*sum(x[1][1:len(x[1])])) elif len(x[0])==1: print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0]) else: x[0].sort(reverse = True) print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0] + sum(x[0][1:len(x[0])])) ``` No
20,464
[ -0.02728271484375, 0.0516357421875, 0.274658203125, 0.2027587890625, -0.4013671875, -0.474853515625, -0.2130126953125, 0.25390625, -0.1314697265625, 0.7529296875, 0.90966796875, 0.1697998046875, 0.53271484375, -0.84521484375, -0.41748046875, 0.01776123046875, -0.8857421875, -0.3027...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Submitted Solution: ``` x = {1:[],0:[]} for _ in range(int(input())): tp, d = map(int,input().split()) if d<0: x[tp] = list(filter(lambda a: a!=(-1*d), x[tp])) if len(x[1]) == 0: print(sum(x[0])) elif len(x[1]) == 1: if len(x[0])==0: print(x[1][0]) elif len(x[0])==1: print(x[1][0] + 2*x[0][0]) else: x[0].sort(reverse=True) print(x[1][0] + 2*x[0][0] + sum(x[0][1:len(x[0])])) else: if len(x[0])==0: print(x[1][0]+ 2*sum(x[1][1:len(x[1])])) elif len(x[0])==1: print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0]) else: x[0].sort(reverse = True) x[1].sort() print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0] + sum(x[0][1:len(x[0])])) else: x[tp].append(d) if len(x[1]) == 0: print(sum(x[0])) elif len(x[1]) == 1: if len(x[0])==0: print(x[1][0]) elif len(x[0])==1: print(x[1][0] + 2*x[0][0]) else: x[0].sort(reverse=True) print(x[1][0] + 2*x[0][0] + sum(x[0][1:len(x[0])])) else: if len(x[0])==0: print(x[1][0]+ 2*sum(x[1][1:len(x[1])])) elif len(x[0])==1: print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0]) else: x[0].sort(reverse = True) x[1].sort() print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0] + sum(x[0][1:len(x[0])])) ``` No
20,465
[ -0.02728271484375, 0.0516357421875, 0.274658203125, 0.2027587890625, -0.4013671875, -0.474853515625, -0.2130126953125, 0.25390625, -0.1314697265625, 0.7529296875, 0.90966796875, 0.1697998046875, 0.53271484375, -0.84521484375, -0.41748046875, 0.01776123046875, -0.8857421875, -0.3027...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Submitted Solution: ``` class BalancingTree: def __init__(self, n): self.N = n self.root = self.node(1<<n, 1<<n) def debug(self): def debug_info(nd_): return (nd_.value - 1, nd_.pivot , nd_.left.value - 1 if nd_.left else -1, nd_.right.value - 1 if nd_.right else -1,nd_.cnt) def debug_node(nd): re = [] if nd.left: re += debug_node(nd.left) if nd.value: re.append(debug_info(nd)) if nd.right: re += debug_node(nd.right) return re print("Debug - root =", self.root.value - 1, debug_node(self.root)[:50]) def append(self, v): v += 1 nd = self.root while True: if v == nd.value: return 0 else: nd.cnt+=1 nd.sum+=v-1 mi, ma = min(v, nd.value), max(v, nd.value) if mi < nd.pivot: nd.value = ma if nd.left: nd = nd.left v = mi else: p = nd.pivot nd.left = self.node(mi, p - (p&-p)//2) break else: nd.value = mi if nd.right: nd = nd.right v = ma else: p = nd.pivot nd.right = self.node(ma, p + (p&-p)//2) break def kth(self,k): cnt=k nd=self.root while True: if nd.left: if nd.left.cnt<k: k-=nd.left.cnt+1 if nd.right: nd=nd.right else: raise IndexError("BalancingTree doesn't hold kth number") elif nd.left.cnt==k: return nd.value-1 else: nd=nd.left else: if k==0: return nd.value-1 if nd.right: k-=1 nd=nd.right else: raise IndexError("BalancingTree doesn't hold kth number") def kth_sum(self,k): if k==-1: return 0 cnt=k res_sum=0 nd=self.root while True: if nd.left: if nd.left.cnt<k: k-=nd.left.cnt+1 res_sum+=nd.left.sum+nd.value-1 if nd.right: nd=nd.right else: raise IndexError("BalancingTree doesn't hold kth number") elif nd.left.cnt==k: res_sum+=nd.left.sum+nd.value-1 return res_sum else: nd=nd.left else: if k==0: return res_sum+nd.value-1 if nd.right: k-=1 res_sum+=nd.value-1 nd=nd.right else: print(cnt,self.size,nd.value-1,nd.right) self.debug() raise IndexError("BalancingTree doesn't hold kth number") def kth_sum_big(self,k): res_sum=self.sum if self.size>k: res_sum-=self.kth_sum(self.size-k-2) print(self.size-k-2,self.kth_sum(self.size-k-2)) return res_sum else: raise IndexError("BalancingTree doesn't hold kth number") def leftmost(self, nd): if nd.left: return self.leftmost(nd.left) return nd def rightmost(self, nd): if nd.right: return self.rightmost(nd.right) return nd def find_l(self, v): v += 1 nd = self.root prev = 0 if nd.value < v: prev = nd.value while True: if v <= nd.value: if nd.left: nd = nd.left else: return prev - 1 else: prev = nd.value if nd.right: nd = nd.right else: return prev - 1 def find_r(self, v): v += 1 nd = self.root prev = 0 if nd.value > v: prev = nd.value while True: if v < nd.value: prev = nd.value if nd.left: nd = nd.left else: return prev - 1 else: if nd.right: nd = nd.right else: return prev - 1 @property def max(self): return self.find_l((1<<self.N)-1) @property def min(self): return self.find_r(-1) @property def sum(self): return self.root.sum-self.root.value+1 @property def size(self): return self.root.cnt-1 def delete(self, v, nd = None, prev = None): v += 1 if not nd: nd = self.root if not prev: prev = nd while v != nd.value: prev = nd nd.cnt-=1 nd.sum-=v-1 if v <= nd.value: if nd.left: nd = nd.left else: return else: if nd.right: nd = nd.right else: return nd.cnt-=1 nd.sum-=v-1 if (not nd.left) and (not nd.right): if not prev.left: prev.right=None elif not prev.right: prev.left=None else: if nd.pivot==prev.left.pivot: prev.left=None else: prev.right=None elif nd.right: nd.value = self.leftmost(nd.right).value self.delete(nd.value - 1, nd.right, nd) else: nd.value = self.rightmost(nd.left).value self.delete(nd.value - 1, nd.left, nd) def __contains__(self, v: int) -> bool: return self.find_r(v - 1) == v class node: def __init__(self, v, p): self.value = v self.pivot = p self.left = None self.right = None self.cnt=1 self.sum=v-1 import sys input=sys.stdin.readline n=int(input()) xybst=BalancingTree(30) xbst=BalancingTree(30) ybst=BalancingTree(30) x,y=0,0 S=0 for _ in range(n): t,d=map(int,input().split()) if d<0: if t==0: xbst.delete(abs(d)) x-=1 else: ybst.delete(abs(d)) y-=1 xybst.delete(abs(d)) else: if t==0: xbst.append(d) x+=1 else: ybst.append(d) y+=1 xybst.append(abs(d)) S+=d if x==0: if y==0: print(0) else: print(2*S-ybst.min) else: if y==0: print(S) else: tmp,tmpy=xybst.kth_sum_big(y-1),ybst.kth_sum_big(y-1) if tmp==tmpy: print(S+tmp-ybst.min+xbst.max) else: print(S+tmp) ``` No
20,466
[ -0.02728271484375, 0.0516357421875, 0.274658203125, 0.2027587890625, -0.4013671875, -0.474853515625, -0.2130126953125, 0.25390625, -0.1314697265625, 0.7529296875, 0.90966796875, 0.1697998046875, 0.53271484375, -0.84521484375, -0.41748046875, 0.01776123046875, -0.8857421875, -0.3027...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order. For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells: * first, second, third. This order deals 5 + 1 + 2 β‹… 8 = 22 damage; * first, third, second. This order deals 5 + 8 + 2 β‹… 1 = 15 damage; * second, first, third. This order deals 1 + 2 β‹… 5 + 8 = 19 damage; * second, third, first. This order deals 1 + 2 β‹… 8 + 2 β‹… 5 = 27 damage; * third, first, second. This order deals 8 + 2 β‹… 5 + 1 = 19 damage; * third, second, first. This order deals 8 + 2 β‹… 1 + 2 β‹… 5 = 20 damage. Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows. Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of changes to the spell set. Each of the next n lines contains two integers tp and d (0 ≀ tp_i ≀ 1; -10^9 ≀ d ≀ 10^9; d_i β‰  0) β€” the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power). Output After each change, print the maximum damage Polycarp can deal with his current set of spells. Example Input 6 1 5 0 10 1 -5 0 5 1 11 0 -10 Output 5 25 10 15 36 21 Submitted Solution: ``` i = int(input()) spell_book = [] def spell_damage(spells): damage = 0 lightning_mult = 0 sspells = sorted(spells, key=lambda x: x[0], reverse=True) if len(spells) > 1: if spells[0][0] == spells[1][0]: spells[0][1], spells[1][1] = spells[1][1], spells[0][1] for spell in sspells: if lightning_mult == 1: damage += spell[1] * 2 lightning_mult = 0 elif lightning_mult == 0: damage += spell[1] if spell[0] == 1: lightning_mult = 1 print(damage) for x in range(i): tp, d = [int(x) for x in input().split()] if d > 0: spell_book.append([tp, d]) elif d < 0: spell_book.remove([tp, abs(d)]) spell_damage(spell_book) ``` No
20,467
[ -0.02728271484375, 0.0516357421875, 0.274658203125, 0.2027587890625, -0.4013671875, -0.474853515625, -0.2130126953125, 0.25390625, -0.1314697265625, 0.7529296875, 0.90966796875, 0.1697998046875, 0.53271484375, -0.84521484375, -0.41748046875, 0.01776123046875, -0.8857421875, -0.3027...
24
Provide tags and a correct Python 3 solution for this coding contest problem. "Hey, it's homework time" β€” thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer). Input The first line of the input data contains an integer n (1 ≀ n ≀ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≀ ai ≀ 5000, 1 ≀ i ≀ n). Output Print the only number β€” the minimum number of changes needed to get the permutation. Examples Input 3 3 1 2 Output 0 Input 2 2 2 Output 1 Input 5 5 3 3 3 1 Output 2 Note The first sample contains the permutation, which is why no replacements are required. In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation. In the third sample we can replace the second element with number 4 and the fourth element with number 2. Tags: greedy Correct Solution: ``` n = int(input()) ns = [int(x) for x in input().split()] ok = [False]*n for ni in ns: ni-=1 if ni<n: ok[ni]=True print(sum([1 for isOK in ok if not isOK])) ```
21,363
[ 0.43017578125, 0.2041015625, 0.084716796875, 0.061126708984375, -0.53125, -0.50146484375, -0.387451171875, -0.06939697265625, 0.359130859375, 0.61181640625, 1.0947265625, -0.329833984375, 0.18701171875, -0.9267578125, -0.86279296875, -0.129150390625, -0.826171875, -0.87451171875, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. "Hey, it's homework time" β€” thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer). Input The first line of the input data contains an integer n (1 ≀ n ≀ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≀ ai ≀ 5000, 1 ≀ i ≀ n). Output Print the only number β€” the minimum number of changes needed to get the permutation. Examples Input 3 3 1 2 Output 0 Input 2 2 2 Output 1 Input 5 5 3 3 3 1 Output 2 Note The first sample contains the permutation, which is why no replacements are required. In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation. In the third sample we can replace the second element with number 4 and the fourth element with number 2. Tags: greedy Correct Solution: ``` n = int(input()) nums = set(map(int, input().split())) count = 0 for i in range(1, n + 1): if i not in nums: count += 1 print(count) ```
21,364
[ 0.451171875, 0.1922607421875, 0.03594970703125, 0.06732177734375, -0.52978515625, -0.488525390625, -0.416015625, -0.0972900390625, 0.37060546875, 0.638671875, 1.0810546875, -0.345703125, 0.192626953125, -0.89208984375, -0.8388671875, -0.1490478515625, -0.8037109375, -0.88134765625,...
24