message
stringlengths
2
43.5k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
853
107k
cluster
float64
24
24
__index_level_0__
int64
1.71k
214k
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3
instruction
0
46,312
24
92,624
Tags: dp, greedy Correct Solution: ``` '''input 5 20 45 -6 34 -15 10 34 1 27 40 -45 ''' import sys from collections import defaultdict as dd 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, r = ri() eventspos = [] eventsneg = [] for i in range(n): temp =ri() if temp[1]>=0: eventspos.append(temp) else: eventsneg.append(temp) eventspos.sort() eventsneg.sort(key = lambda x: x[0]+x[1]) eventsneg.reverse() status =1 ans=0 for i in range(len(eventspos)): if eventspos[i][0] <= r: r+= eventspos[i][1] ans+=1 else: status = 0 check = [0 for i in range(r+1)] #print(eventsneg) for i in range(len(eventsneg)): for j in range(eventsneg[i][0] , r+1): if j+eventsneg[i][1]>=0: check[j+eventsneg[i][1]] = max(check[j+eventsneg[i][1]] , check[j]+1) # if status and r>=0 and sum(check)==len(check): # print("YES") # else: # print("NO") #print(eventsneg,eventspos) print(max(check) + ans ) ```
output
1
46,312
24
92,625
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3
instruction
0
46,313
24
92,626
Tags: dp, greedy Correct Solution: ``` # Enter your code here. Read input from STDIN. Print output to STDOUT# =============================================================================================== # importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from itertools import * import bisect from heapq import * from math import ceil, floor from copy import * from collections import deque, defaultdict from collections import Counter as counter # Counter(list) return a dict with {key: count} from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)] from itertools import permutations as permutate from bisect import bisect_left as bl from operator import * # If the element is already present in the list, # the left most position where element has to be inserted is returned. from bisect import bisect_right as br from bisect import bisect # If the element is already present in the list, # the right most position where element has to be inserted is returned # ============================================================================================== # fast I/O region BUFSIZE = 8192 from sys import stderr 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") # =============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### # =============================================================================================== # some shortcuts mod = 1000000007 def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def out(var): sys.stdout.write(str(var)) # for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) def fsep(): return map(float, inp().split()) def nextline(): out("\n") # as stdout.write always print sring. def testcase(t): for p in range(t): solve() def pow(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0): return 0 while (y > 0): if ((y & 1) == 1): # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res from functools import reduce def factors(n): return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))) def gcd(a, b): if a == b: return a while b > 0: a, b = b, a % b return a # discrete binary search # minimise: # def search(): # l = 0 # r = 10 ** 15 # # for i in range(200): # if isvalid(l): # return l # if l == r: # return l # m = (l + r) // 2 # if isvalid(m) and not isvalid(m - 1): # return m # if isvalid(m): # r = m + 1 # else: # l = m # return m # maximise: # def search(): # l = 0 # r = 10 ** 15 # # for i in range(200): # # print(l,r) # if isvalid(r): # return r # if l == r: # return l # m = (l + r) // 2 # if isvalid(m) and not isvalid(m + 1): # return m # if isvalid(m): # l = m # else: # r = m - 1 # return m #to find factorial and ncr # N=100000 # mod = 10**9 +7 # fac = [1, 1] # finv = [1, 1] # inv = [0, 1] # # for i in range(2, N + 1): # fac.append((fac[-1] * i) % mod) # inv.append(mod - (inv[mod % i] * (mod // i) % mod)) # finv.append(finv[-1] * inv[-1] % mod) # # # def comb(n, r): # if n < r: # return 0 # else: # return fac[n] * (finv[r] * finv[n - r] % mod) % mod ##############Find sum of product of subsets of size k in a array # ar=[0,1,2,3] # k=3 # n=len(ar)-1 # dp=[0]*(n+1) # dp[0]=1 # for pos in range(1,n+1): # dp[pos]=0 # l=max(1,k+pos-n-1) # for j in range(min(pos,k),l-1,-1): # dp[j]=dp[j]+ar[pos]*dp[j-1] # print(dp[k]) def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10] return list(accumulate(ar)) def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4] return list(accumulate(ar[::-1]))[::-1] def N(): return int(inp()) dx=[0,0,1,-1] dy=[1,-1,0,0] # ========================================================================================= from collections import defaultdict def numberOfSetBits(i): i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24 from decimal import * def solve(): class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (_size) + data + [default] * (_size - self._len) for i in range(_size - 1, -1, -1): self.data[i] = func(self.data[2 * i], self.data[2 * i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) n,r=sep() posrat=[] negrat=[] c=0 for _ in range(n): a,b=sep() if b>=0: posrat.append((a,b)) else: negrat.append((a,b)) posrat.sort() def f(x): return x[0]+x[1] negrat.sort(reverse=True,key=f) cr=r for i in posrat: ai,bi=i if ai<=cr: c+=1 cr+=bi l=len(negrat) R=cr dp=[[0]*(R+1) for _ in range(l+1)] for i in range(1,l+1): for j in range(R,-1,-1): dp[i][j]=dp[i-1][j] if j-negrat[i-1][1]>=negrat[i-1][0] and j-negrat[i-1][1]<=R: dp[i][j]=max(dp[i][j],dp[i-1][j-negrat[i-1][1]]+1) m=0 for i in range(1,l+1): for j in range(R,-1,-1): m=max(m,dp[i][j]) print(m+c) solve() #testcase(int(inp())) ```
output
1
46,313
24
92,627
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3
instruction
0
46,314
24
92,628
Tags: dp, greedy Correct Solution: ``` from functools import reduce def doProject(r, proj, nproj): count=0 for i in range(len(proj)): if(proj[i][0]<=r): r+=proj[i][1] count+=1 else: pass dp=[[0 for j in range(r+1)] for i in range(len(nproj)+1)] dp[0][r] = count for i in range(len(nproj)): for cr in range(r+1): if(nproj[i][0] <= cr and cr + nproj[i][1] >= 0): dp[i+1][cr + nproj[i][1]] = max(dp[i+1][cr + nproj[i][1]], dp[i][cr]+1) dp[i+1][cr] = max(dp[i+1][cr], dp[i][cr]) count = reduce(lambda x,y: max(x,y) , dp[len(nproj)]) return count def main(): n, r = map(int, input().rstrip().split()) proj, nproj = [], [] for _ in range(n): temp = list(map(int, input().rstrip().split())) if(temp[1]<0): nproj.append(temp) else: proj.append(temp) proj.sort() nproj.sort(reverse=True, key=lambda x: x[0]+x[1]) ans = doProject(r,proj, nproj) print(ans) if __name__ == "__main__": main() ```
output
1
46,314
24
92,629
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3
instruction
0
46,315
24
92,630
Tags: dp, greedy Correct Solution: ``` import sys input = sys.stdin.readline n, r = map(int, input().split()) l = [] for _ in range(n): l.append(list(map(int, input().split()))) p = 0 ans = 0 while (p < n): if l[p][0] <= r and l[p][1] >= 0: r += l[p][1] l = l[:p] + l[p + 1:] p = 0 n -= 1 ans += 1 else: p += 1 if l == []: print(ans) exit(0) q = len(l) for i in range(q): l[i][0] = max(l[i][0], -l[i][1]) l = sorted(l, key = lambda x: x[0] + x[1]) l.reverse() #print(l, r) dp = [[0 for _ in range(r + 1)] for _ in range(q + 1)] for i in range(q): for j in range(r + 1): #dp[i][j] = dp[i][j-1] if j >= l[i][0] and 0 <= j + l[i][1] <= r: dp[i+1][j+l[i][1]] = max(dp[i+1][j+l[i][1]], dp[i][j] + 1) dp[i+1][j] = max(dp[i+1][j], dp[i][j]) # for i,x in enumerate(dp): # print(i, *x) print(max(dp[-1]) + ans) ```
output
1
46,315
24
92,631
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3
instruction
0
46,316
24
92,632
Tags: dp, greedy Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Thu Jan 9 11:12:02 2020 @author: Rodro """ inp = str(input()).split() size = int(inp[0]) r = int(inp[1]) pos = [] neg = [] for i in range(size): inp = str(input()).split() a = int(inp[0]) b = int(inp[1]) if b >= 0: pos.append((a, b)) else: neg.append((a,b)) pos = sorted(pos) projects = 0 for ab in pos: a, b = ab if r >= a: r += b projects += 1 else: break neg = sorted(neg, key = lambda ab: ab[0] + ab[1], reverse = True) n = len(neg) dp = [[0]*(r + 1) for _ in range(n + 1)] dp[0][r] = projects for i in range(0, n): for j in range(0, r + 1): if j >= neg[i][0] and j + neg[i][1] >= 0: dp[i + 1][j + neg[i][1]] = max(dp[i + 1][j + neg[i][1]], dp[i][j] + 1) dp[i + 1][j] = max(dp[i + 1][j], dp[i][j]) print(max(dp[n])) ```
output
1
46,316
24
92,633
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3
instruction
0
46,317
24
92,634
Tags: dp, greedy Correct Solution: ``` #https://codeforces.com/contest/1203/problem/F2 n, r = map(int, input().split()) arr = [list(map(int, input().split())) for _ in range(n)] def solve1(cur, arr): cnt=0 while len(arr) > 0: max_inc = -9999 choose = None for a, b in arr: if cur >= a and max_inc < b: max_inc = b choose = a if choose is None: flg=False break cnt+=1 cur+=max_inc arr.remove([choose, max_inc]) return cur, cnt arr1 = [[x, y] for x, y in arr if y >= 0] arr2 = [[x, y] for x, y in arr if y < 0] r, cnt = solve1(r, arr1) n = len(arr2) arr2 = [[]] + sorted(arr2, key=lambda x:x[0]+x[1], reverse=True) dp = [[-1] * (n+1) for _ in range(n+1)] for i in range(n+1): dp[i][0] = r for i in range(1, n+1): for j in range(1, i+1): dp[i][j] = dp[i-1][j] if dp[i-1][j-1] >= arr2[i][0] and dp[i-1][j-1] + arr2[i][1] >= 0: dp[i][j] = max(dp[i][j], dp[i-1][j-1]+arr2[i][1]) ans = 0 for j in range(n+1): if dp[n][j] >= 0: ans = j print(ans+cnt) #3 4 #4 6 #10 -2 #8 -1 ```
output
1
46,317
24
92,635
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3
instruction
0
46,318
24
92,636
Tags: dp, greedy Correct Solution: ``` n, r = map(int, input().split()) a = [] cnt = 0 for i in range(n): a.append([int(j) for j in input().split()]) flag = True while flag: flag = False for i in a: if r >= i[0] and i[1] >= 0: flag = True r += i[1] cnt += 1 a.remove(i) break a = sorted(a, key=lambda x: x[0] + x[1]) dp = [[0] * (r + 1) for i in range(len(a) + 1)] for i in range(len(a)): for j in range(r + 1): dp[i][j] = dp[i - 1][j] if j >= a[i][0] and j + a[i][1] >= 0: dp[i][j] = max(dp[i][j], dp[i - 1][j + a[i][1]] + 1) print(cnt + dp[len(a) - 1][r]) #print(dp, a) ```
output
1
46,318
24
92,637
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3 Submitted Solution: ``` import math import sys from collections import defaultdict # input = sys.stdin.readline nt = lambda: map(int, input().split()) def main(): n, r = nt() projects = [tuple(nt()) for _ in range(n)] positive = [t for t in projects if t[1] > 0] negative = [t for t in projects if t[1] <= 0] max_pos = 0 for p in sorted(positive): if p[0] <= r: r += p[1] max_pos += 1 else: break negative.sort(key=lambda x: -x[0] - x[1]) MAX = 60001 dp = [[-1 for _ in range(MAX)] for _ in range(len(negative)+1)] dp[0][r] = 0 for i in range(len(negative)): for j in range(MAX): if dp[i][j] == -1: continue dp[i+1][j] = max(dp[i+1][j], dp[i][j]) if j >= negative[i][0] and j+negative[i][1] >= 0: dp[i+1][j+negative[i][1]] = max(dp[i+1][j+negative[i][1]], dp[i][j]+1) max_neg = 0 for i in range(MAX): max_neg = max(max_neg, dp[len(negative)][i]) print(max_pos + max_neg) if __name__ == '__main__': main() ```
instruction
0
46,319
24
92,638
Yes
output
1
46,319
24
92,639
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3 Submitted Solution: ``` def myFunc(e): return e[0] + e[1] count, rating = map(int, input().split()) goodJob = [] badJob = [] taken = 0 for i in range(count): a, b = map(int, input().split()) if b >= 0: goodJob.append([a, b]) else: badJob.append([a, b]) goodJob.sort() badJob.sort(reverse=True, key=myFunc) for job in goodJob: if job[0] <= rating: rating += job[1] taken += 1 else: break dp = [] for i in range(len(badJob) + 1): row = [] for j in range(rating + 2): row.append(0) dp.append(row) dp[0][rating] = taken for i in range(len(badJob)): for curRating in range(rating + 1): if curRating >= badJob[i][0] and curRating + badJob[i][1] >= 0: dp[i + 1][curRating + badJob[i][1]] = max(dp[i + 1][curRating + badJob[i][1]], dp[i][curRating] + 1) dp[i + 1][curRating] = max(dp[i + 1][curRating], dp[i][curRating]) ans = 0 for curRating in range(rating + 1): ans = max(ans, dp[len(badJob)][curRating]) print(ans) ```
instruction
0
46,320
24
92,640
Yes
output
1
46,320
24
92,641
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3 Submitted Solution: ``` from sys import stdin from sys import setrecursionlimit as SRL; SRL(10**7) rd = stdin.readline rrd = lambda: map(int, rd().strip().split()) n,r = rrd() pos = [] neg = [] for i in range(n): a,b = rrd() if b < 0: neg.append([a,b]) else: pos.append([a,b]) pos.sort(key=lambda x: x[0]) neg.sort(key=lambda x: x[0]+x[1]) ans = 0 for a,b in pos: if r>=a: r += b ans += 1 else: break dp = [[0]*105 for _i in range(60005)] for i in range(r+10): for j in range(len(neg)): if i >= neg[j][0] and i+neg[j][1] >= 0: if j: dp[i][j] = max(dp[i][j], dp[i + neg[j][1]][j - 1] + 1,dp[i][j-1]) else: dp[i][j] = 1 else: if j: dp[i][j] = dp[i][j-1] print(dp[r][len(neg)-1] + ans) ```
instruction
0
46,321
24
92,642
Yes
output
1
46,321
24
92,643
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3 Submitted Solution: ``` from bisect import bisect_right n,r = map(int, input().split()) aa = [0]*n bb = [0]*n for i in range(n): aa[i], bb[i] = map(int, input().split()) ppi = [(aa[i], bb[i]) for i in range(n) if bb[i] >= 0] ppd = [(max(aa[i], -bb[i]), bb[i]) for i in range(n) if bb[i] < 0] ppi.sort() count = 0 for (a,b) in ppi: if a > r: break r += b count+=1 ppd.sort(reverse=True,key=lambda p: p[0] + p[1] ) dp = [[0]*(r+1) for _ in range(len(ppd)+1)] dp[0][r] = count for i,(a,b) in enumerate(ppd): for v in range(r+1): if v >= a and v+b >= 0: dp[i+1][v + b] = max(dp[i+1][v + b], dp[i][v] + 1) dp[i+1][v] = max(dp[i+1][v], dp[i][v]) print(max(dp[len(ppd)])) ```
instruction
0
46,322
24
92,644
Yes
output
1
46,322
24
92,645
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3 Submitted Solution: ``` def myFunc(e): return e[0] + e[1] count, rating = map(int, input().split()) goodJob = [] badJob = [] taken = 0 for i in range(count): a, b = map(int, input().split()) if b >= 0: goodJob.append([a, b]) else: badJob.append([a, b]) goodJob.sort() badJob.sort(reverse=True, key=myFunc) for job in goodJob: if job[0] <= rating: rating += job[1] taken += 1 else: break dp = [] for i in range(len(badJob) + 1): row = [] for j in range(rating + 2): row.append(0) dp.append(row) dp[0][rating] = taken for i in range(len(badJob)): for curRating in range(rating): if curRating >= badJob[i][0] and curRating + badJob[i][1] >= 0: dp[i + 1][curRating + badJob[i][1]] = max(dp[i + 1][curRating + badJob[i][1]], dp[i][curRating] + 1) dp[i + 1][curRating] = max(dp[i + 1][curRating], dp[i][curRating]) ans = 0 for curRating in range(rating + 1): ans = max(ans, dp[len(badJob)][curRating]) print(ans + taken) ```
instruction
0
46,323
24
92,646
No
output
1
46,323
24
92,647
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3 Submitted Solution: ``` from bisect import bisect_right n,r = map(int, input().split()) aa = [0]*n bb = [0]*n for i in range(n): aa[i], bb[i] = map(int, input().split()) avail = set(range(n)) fr = r + sum(bb) count = 0 for i in range(n): nxt = -1 for j in avail: if aa[j] <= r and bb[j] >= 0: nxt = j break if nxt == -1: break avail.remove(nxt) r += bb[nxt] count += 1 pp = [(aa[i], bb[i]) for i in avail if aa[i] <= r and bb[i] < 0 and -bb[i] <= r] pp.sort() while len(pp) > 0: maxc = -1 imaxc = -1 (aa, bb) = zip(*pp) for i in range(len(pp)): c = bisect_right(aa, r + bb[i]) if c > i: c-=1 if c > maxc: maxc = c imaxc = i count+=1 r += bb[imaxc] del pp[imaxc] del pp[maxc:] pp = [(a, b) for (a, b) in pp if -b <=r] print(count) ```
instruction
0
46,324
24
92,648
No
output
1
46,324
24
92,649
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3 Submitted Solution: ``` def myFunc(e): return e[0] + e[1] count, rating = map(int, input().split()) goodJob = [] badJob = [] l1 = 0 l2 = 0 for i in range(count): a, b = map(int, input().split()) if b >= 0: goodJob.append([a, b]) else: badJob.append([a, b]) goodJob.sort() badJob.sort(reverse=True, key=myFunc) for job in range(len(goodJob)): if goodJob[job][0] <= rating: rating += goodJob[job][1] else: l1 = job + 1 break if l1 == 0: l1 = len(goodJob) for job in range(len(badJob)): if badJob[job][0] <= rating: rating += badJob[job][1] else: l2 = job + 1 break if l2 == 0: l2 = len(badJob) print(l1 + l2) ```
instruction
0
46,325
24
92,650
No
output
1
46,325
24
92,651
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. Input The first line of the input contains two integers n and r (1 ≀ n ≀ 100, 1 ≀ r ≀ 30000) β€” the number of projects and the initial rating of Polycarp, respectively. The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 ≀ a_i ≀ 30000, -300 ≀ b_i ≀ 300) β€” the rating required to complete the i-th project and the rating change after the project completion. Output Print one integer β€” the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. Examples Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3 Submitted Solution: ``` import sys input = sys.stdin.readline n, r = map(int, input().split()) l = [] for _ in range(n): l.append(list(map(int, input().split()))) p = 0 ans = 0 while (p < n): if l[p][0] <= r and l[p][1] >= 0: r += l[p][1] l = l[:p] + l[p + 1:] p = 0 n -= 1 ans += 1 else: p += 1 if l == []: print(ans) exit(0) q = len(l) for i in range(q): l[i][0] = max(l[i][0], -l[i][1]) l = sorted(l, key = lambda x: x[0] + x[1]) l.reverse() #print(l, r) for i in range(len(l)): if l[i][0] > r: continue else: r += l[i][1] ans += 1 print(ans) ```
instruction
0
46,326
24
92,652
No
output
1
46,326
24
92,653
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
instruction
0
46,657
24
93,314
Tags: binary search, data structures, dp Correct Solution: ``` import collections maxa = 10**9 def main(): n, k = [int(s) for s in input().split()] alist = [int(s) for s in input().split()] if k == 1: a_ct = collections.Counter(alist) print(sum(c*(c-1)*(c-2)//6 for a,c in a_ct.items())) return ca = collections.Counter() caak = collections.Counter() ans = 0 for a in alist: if a % k == 0 and (a//k) % k == 0: ans += caak[(a//k)//k] if a % k == 0: caak[a//k] += ca[a//k] ca[a] += 1 print(ans) main() ```
output
1
46,657
24
93,315
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
instruction
0
46,658
24
93,316
Tags: binary search, data structures, dp Correct Solution: ``` n, k = (int(x) for x in input().split()) a = [int(x) for x in input().split()] D = {} amount = 0 for x in a: if not x in D: D[x] = [0, 0] t = D[x//k] if x%k == 0 and x//k in D else [0,0] D[x][1] += t[0] D[x][0] += 1 if x != 0 : amount += t[1] C_k_3 = lambda n : n * (n -1) * (n - 2) // 6 if k != 1: print(amount + C_k_3(D.get(0,[0,0])[0])) else: print(sum([C_k_3(D[x][0]) for x in D])) ```
output
1
46,658
24
93,317
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
instruction
0
46,659
24
93,318
Tags: binary search, data structures, dp Correct Solution: ``` # -*- coding: utf-8 -*- # Baqir Khan # Software Engineer (Backend) from collections import defaultdict from sys import stdin inp = stdin.readline n, k = map(int, inp().split()) a = list(map(int, inp().split())) left = [0] * n freq_left = defaultdict(int) right = [0] * n freq_right = defaultdict(int) ans = 0 for i in range(n): if a[i] % k == 0 and freq_left[a[i] // k] > 0: left[i] = freq_left[a[i] // k] freq_left[a[i]] += 1 for i in range(n - 1, -1, -1): if freq_right[a[i] * k] > 0: right[i] = freq_right[a[i] * k] freq_right[a[i]] += 1 for i in range(n): if left[i] > 0 and right[i] > 0: ans += left[i] * right[i] print(ans) ```
output
1
46,659
24
93,319
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
instruction
0
46,660
24
93,320
Tags: binary search, data structures, dp Correct Solution: ``` from collections import Counter from collections import defaultdict def mp(): return map(int,input().split()) def lt(): return list(map(int,input().split())) def pt(x): print(x) def ip(): return input() def it(): return int(input()) def sl(x): return [t for t in x] def spl(x): return x.split() def aj(liste, item): liste.append(item) def bin(x): return "{0:b}".format(x) def listring(l): return ' '.join([str(x) for x in l]) def printlist(l): print(' '.join([str(x) for x in l])) n,k = mp() a = lt() c = Counter(a) result = 0 A = defaultdict(int) B = defaultdict(int) C = defaultdict(int) if k == 1: for i in set(a): result += c[i]*(c[i]-1)*(c[i]-2) print(result//6) exit() for i in range(n): x = a[i] if x == 0: temp = A[0] temp1 = B[0] A[0],B[0],C[0] = A[0]+1,B[0]+temp,C[0]+temp1 else: A[x] += 1 B[x] += A[x/k] C[x] += B[x/k] for i in C: result += C[i] print(result) ```
output
1
46,660
24
93,321
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
instruction
0
46,661
24
93,322
Tags: binary search, data structures, dp Correct Solution: ``` from collections import defaultdict import time if __name__ == "__main__": n , k = [int(x) for x in input().split()] nums = [int(x) for x in input().split()] #n , k = 200000 , 1 #nums = [1 for i in range(n)] #t1 = time.time() left = [0]*len(nums) predict = defaultdict( int ) for i in range( len(nums) ): num = nums[i] if num%k == 0: left[i] = predict[num//k] predict[num] += 1 #print( i , ":" , predict ) right = [0]*len(nums) nextdict = defaultdict( int ) for i in range( len(nums) - 1 , -1 , -1 ): num = nums[i] right[i] = nextdict[num*k] nextdict[num] += 1 #print( "left :" , left ) #print( "right :" , right ) print( sum([left[i]*right[i] for i in range(len(nums))]) ) #t2 = time.time() #print( t2-t1 , "s" ) ```
output
1
46,661
24
93,323
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
instruction
0
46,662
24
93,324
Tags: binary search, data structures, dp Correct Solution: ``` from collections import Counter n,k=map(int, input().split()) a=list(map(int, input().split())) left={} ans=0 right=Counter(a) for i in range(n): if right[a[i]]>0: right[a[i]]-=1 if a[i]%k==0: t1=a[i]//k t2=a[i]*k if t1 in left and t2 in right: ans+=(left[t1]*right[t2]) try: left[a[i]]+=1 except: left[a[i]]=1 print(ans) ```
output
1
46,662
24
93,325
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
instruction
0
46,663
24
93,326
Tags: binary search, data structures, dp Correct Solution: ``` from collections import Counter def solve(n, k, arr): c1 = Counter() c2 = Counter() total = 0 for a in reversed(arr): total += c2[a*k] c2[a] += c1[a*k] c1[a] += 1 return total n, k = map(int, input().split()) arr = list(map(int, input().split())) print(solve(n, k, arr)) ```
output
1
46,663
24
93,327
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
instruction
0
46,664
24
93,328
Tags: binary search, data structures, dp Correct Solution: ``` l=input().split() n=int(l[0]) k=int(l[1]) l=input().split() li=[int(i) for i in l] hashipref=dict() hashisuff=dict() for i in range(n-1,0,-1): if(li[i] not in hashisuff): hashisuff[li[i]]=1 else: hashisuff[li[i]]+=1 ans=0 for i in range(1,n): if(li[i-1] not in hashipref): hashipref[li[i-1]]=0 hashipref[li[i-1]]+=1 hashisuff[li[i]]-=1 if(li[i]%k==0 and li[i]//k in hashipref and li[i]*k in hashisuff): ans+=(hashipref[li[i]//k]*hashisuff[li[i]*k]) print(ans) ```
output
1
46,664
24
93,329
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4. Submitted Solution: ``` import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions,statistics from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal from sys import stdout from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest # sys.setrecursionlimit(111111) INF=999999999999999999999999 alphabets="abcdefghijklmnopqrstuvwxyz" 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)) class SegTree: def __init__(self, n): self.N = 1 << n.bit_length() self.tree = [0] * (self.N<<1) def update(self, i, j, v): i += self.N j += self.N while i <= j: if i%2==1: self.tree[i] += v if j%2==0: self.tree[j] += v i, j = (i+1) >> 1, (j-1) >> 1 def query(self, i): v = 0 i += self.N while i > 0: v += self.tree[i] i >>= 1 return v def SieveOfEratosthenes(limit): """Returns all primes not greater than limit.""" isPrime = [True]*(limit+1) isPrime[0] = isPrime[1] = False primes = [] for i in range(2, limit+1): if not isPrime[i]:continue primes += [i] for j in range(i*i, limit+1, i): isPrime[j] = False return primes def main(): mod=1000000007 # InverseofNumber(mod) # InverseofFactorial(mod) # factorial(mod) starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") tc=1 # Did you look at the constraints dummy? # 1.Greedy? # 2.DP? # 3.Binary Search?(Monotonic? any one directed order in which we have to perform something?) # 4.Graph? # 5.Number Theory?(GCD subtraction?) # 6.Bruteforce?(Redundant part of N which may not give answer?Constraints?) # 7.Range Queries? # 8.Any Equivalency?(We have A and B and have to do # something between them maybe difficult if there was A~C and C~B then A~B # C could be max or min or some other thing) # 9.Reverse Engineering?(From Answer to quesn or last step to first step) tc=1 for _ in range(tc): n,k=ria() a=ria() pos={} ans=0 if k==1: d=Counter(a) for i in d: if d[i]>=3: t=d[i] ans+=(t*(t-1)*(t-2))//6 else: for i in range(n): if a[i] in pos: pos[a[i]].append(i) else: pos[a[i]]=[i] #x,y,z=b/k,b,b*k for i in range(1,n-1): if a[i]%k==0: x=a[i]//k y=a[i]*k if x in pos and y in pos: px=bisect.bisect_left(pos[x],i) py=bisect.bisect_left(pos[y],i+1) ans+=(px)*(len(pos[y])-py) wi(ans) #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main() ```
instruction
0
46,665
24
93,330
Yes
output
1
46,665
24
93,331
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4. Submitted Solution: ``` #from bisect import bisect_left as bl #c++ lowerbound bl(array,element) #from bisect import bisect_right as br #c++ upperbound br(array,element) #from __future__ import print_function, division #while using python2 # from itertools import accumulate from collections import defaultdict, Counter def modinv(n,p): return pow(n,p-2,p) def main(): #sys.stdin = open('input.txt', 'r') #sys.stdout = open('output.txt', 'w') n, k = [int(x) for x in input().split()] series = [int(x) for x in input().split()] ct = Counter(series) ct2 = defaultdict(lambda : 0) ct2[series[0]] += 1 ans = 0 for i in range(1, n-1): x = series[i] lefts = 0 rights = 0 if x % k == 0: lefts = ct2[x//k] ct2[x] += 1 rights = ct[x*k] - ct2[x*k] ans += (lefts * rights) print(ans) #------------------ Python 2 and 3 footer by Pajenegod and c1729----------------------------------------- py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') if __name__ == '__main__': main() ```
instruction
0
46,666
24
93,332
Yes
output
1
46,666
24
93,333
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4. Submitted Solution: ``` import bisect n, k = map(int, input().split()) a = [int(i) for i in input().split()] new_a = set(a) ans = 0 p = {} for i in range(n): p[a[i]] = [] for i in range(n): p[a[i]].append(i) for i in range(n): if a[i] % k == 0: first = a[i] // k second = a[i] * k if first == second and second == a[i]: pos = bisect.bisect_left(p[a[i]], i) ans += pos * (len(p[a[i]]) - pos - 1) else: f = 0 s = 0 if first in new_a: f = bisect.bisect_right(p[first], i) if second in new_a: s = len(p[second]) - bisect.bisect_right(p[second], i) ans += (f * s) print(ans) ```
instruction
0
46,667
24
93,334
Yes
output
1
46,667
24
93,335
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4. Submitted Solution: ``` n,k = map(int,input().split()) a = [int(x) for x in input().split()] otv = 0 mp1 = {} mp2 = {} for x in a: if x in mp2: mp2[x] += 1 else: mp2[x] = 1 for i in range(n): mp2[a[i]] -= 1 if a[i]%k == 0 and (a[i]//k in mp1) and (a[i] * k in mp2): otv += mp1[a[i]//k] * mp2[a[i] * k] if a[i] in mp1: mp1[a[i]] += 1 else: mp1[a[i]] = 1 print(otv) ```
instruction
0
46,668
24
93,336
Yes
output
1
46,668
24
93,337
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4. Submitted Solution: ``` from collections import Counter inp0 = input().split(' ') inp1 = int(inp0[1]) inp2 = list(map(int, input().split(' '))) Result = 0 element = 0 Counter (inp2) for inp in inp2: if (element != 0 and element != len(inp2)-1 and inp % inp1 == 0): print(list(Counter(inp2[:element]))) leftCount = Counter(inp2[:element]).get(inp/inp1) try: rightCount = Counter(inp2[element+1:]).get(inp*inp1) Result += leftCount*rightCount except TypeError: pass element += 1 print(Result) ```
instruction
0
46,669
24
93,338
No
output
1
46,669
24
93,339
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4. Submitted Solution: ``` def calc(a,b,c,l): if a in l: if l.index(a)<len(l)-1: l=l[l.index(a)+1:] p3=calc(a,b,c,l) if b in l: if l.index(b)<len(l)-1: l=l[l.index(b):] p2=calc(b,b,c,l) l.remove(b) if c in l: p1=l.count(c) return max(p1*(p2+p3),1) else : return 0 else: return 0 else: return 0 else : return 0 else: return 0 s=input().split() n=int(s[0]) k=int(s[1]) kk=k*k del s p=0 a=list(map(int,(input().split()))) for e in set(a): p=p+calc(e,k*e,kk*e,a) print(int(p)) ```
instruction
0
46,670
24
93,340
No
output
1
46,670
24
93,341
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4. Submitted Solution: ``` n,k = map(int,input().split()) nums = [int(x) for x in input().split()] zero = {} one = {} ans = 0 for i in range(n): x = nums[i] if x not in zero: zero[x] = 0 zero[x]+=1 if x%k==0: if x//k in zero: if x not in one: one[x] = 0 one[x]+=zero[x//k] if x//k in one: ans+=one[x//k] print(ans) ```
instruction
0
46,671
24
93,342
No
output
1
46,671
24
93,343
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k. A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input The first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence. Output Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k. Examples Input 5 2 1 1 2 2 4 Output 4 Input 3 1 1 1 1 Output 1 Input 10 3 1 2 6 2 3 6 9 18 3 9 Output 6 Note In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4. Submitted Solution: ``` from math import sqrt,gcd,ceil,floor,log,factorial from itertools import permutations,combinations from collections import Counter, defaultdict cnt,pre={},{} n,k = map(int,input().split()) a = list(map(int,input().split())) dp=[0]*n if 1: ans=0 for i in range(n): cnt[a[i]] = cnt.get(a[i],0)+1 if a[i]!=0: dp[i]=pre.get(a[i]//k,0) pre[a[i]]=pre.get(a[i],0)+cnt.get(a[i]//k,0) for i in range(n): if a[i]!=0: if a[i]%k==0 and a[i]%(k*k)==0: ans+=dp[i] zer=cnt.get(0,0) ans+=max((zer*(zer-1)*(zer-2))//6,0) print(ans) ```
instruction
0
46,672
24
93,344
No
output
1
46,672
24
93,345
Provide tags and a correct Python 3 solution for this coding contest problem. In the evening Polycarp decided to analyze his today's travel expenses on public transport. The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops. Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes. It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment. For example, if Polycarp made three consecutive trips: "BerBank" <image> "University", "University" <image> "BerMall", "University" <image> "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus. Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction. What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards? Input The first line contains five integers n, a, b, k, f (1 ≀ n ≀ 300, 1 ≀ b < a ≀ 100, 0 ≀ k ≀ 300, 1 ≀ f ≀ 1000) where: * n β€” the number of Polycarp trips, * a β€” the cost of a regualar single trip, * b β€” the cost of a trip after a transshipment, * k β€” the maximum number of travel cards Polycarp can buy, * f β€” the cost of a single travel card. The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space β€” the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different. Output Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards. Examples Input 3 5 3 1 8 BerBank University University BerMall University BerBank Output 11 Input 4 2 1 300 1000 a A A aa aa AA AA a Output 5 Note In the first example Polycarp can buy travel card for the route "BerBank <image> University" and spend 8 burles. Note that his second trip "University" <image> "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles. In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles.
instruction
0
47,599
24
95,198
Tags: greedy, implementation, sortings Correct Solution: ``` n, a, b, k, f = map(int, input().split()) slov = dict() temp = input().split() slov[frozenset(temp)] = a for i in range(1, n): temp2 = input().split() try: if temp2[0] == temp[1]: slov[frozenset(temp2)] += b else: slov[frozenset(temp2)] += a except KeyError: if temp2[0] == temp[1]: slov[frozenset(temp2)] = b else: slov[frozenset(temp2)] = a temp = temp2 costs = sorted(list(slov.values()), reverse=True) for i in range(min(k, len(costs))): if costs[i] > f: costs[i] = f else: break print(sum(costs)) ```
output
1
47,599
24
95,199
Provide tags and a correct Python 3 solution for this coding contest problem. In the evening Polycarp decided to analyze his today's travel expenses on public transport. The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops. Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes. It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment. For example, if Polycarp made three consecutive trips: "BerBank" <image> "University", "University" <image> "BerMall", "University" <image> "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus. Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction. What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards? Input The first line contains five integers n, a, b, k, f (1 ≀ n ≀ 300, 1 ≀ b < a ≀ 100, 0 ≀ k ≀ 300, 1 ≀ f ≀ 1000) where: * n β€” the number of Polycarp trips, * a β€” the cost of a regualar single trip, * b β€” the cost of a trip after a transshipment, * k β€” the maximum number of travel cards Polycarp can buy, * f β€” the cost of a single travel card. The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space β€” the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different. Output Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards. Examples Input 3 5 3 1 8 BerBank University University BerMall University BerBank Output 11 Input 4 2 1 300 1000 a A A aa aa AA AA a Output 5 Note In the first example Polycarp can buy travel card for the route "BerBank <image> University" and spend 8 burles. Note that his second trip "University" <image> "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles. In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles.
instruction
0
47,600
24
95,200
Tags: greedy, implementation, sortings Correct Solution: ``` n, a, b, k, f = list(map(int, input().split())) totalCost = {} lastStop = '' total = 0 for i in range(n): s1, s2 = input().split() cost = a if lastStop != s1 else b key = (min(s1, s2), max(s1, s2)) if key not in totalCost: totalCost[key] = cost else: totalCost[key] += cost total += cost lastStop = s2 sortedTotalCost = [(totalCost[key], key[0], key[1]) for key in totalCost] sortedTotalCost.sort(reverse=True) i = 0 while i < len(sortedTotalCost) and k > 0 and sortedTotalCost[i][0] > f: total -= sortedTotalCost[i][0] total += f k -= 1 i += 1 print(total) ```
output
1
47,600
24
95,201
Provide tags and a correct Python 3 solution for this coding contest problem. In the evening Polycarp decided to analyze his today's travel expenses on public transport. The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops. Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes. It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment. For example, if Polycarp made three consecutive trips: "BerBank" <image> "University", "University" <image> "BerMall", "University" <image> "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus. Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction. What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards? Input The first line contains five integers n, a, b, k, f (1 ≀ n ≀ 300, 1 ≀ b < a ≀ 100, 0 ≀ k ≀ 300, 1 ≀ f ≀ 1000) where: * n β€” the number of Polycarp trips, * a β€” the cost of a regualar single trip, * b β€” the cost of a trip after a transshipment, * k β€” the maximum number of travel cards Polycarp can buy, * f β€” the cost of a single travel card. The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space β€” the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different. Output Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards. Examples Input 3 5 3 1 8 BerBank University University BerMall University BerBank Output 11 Input 4 2 1 300 1000 a A A aa aa AA AA a Output 5 Note In the first example Polycarp can buy travel card for the route "BerBank <image> University" and spend 8 burles. Note that his second trip "University" <image> "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles. In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles.
instruction
0
47,601
24
95,202
Tags: greedy, implementation, sortings Correct Solution: ``` n,a,b,k,f = [int(i) for i in input().split()] pred = "_" d = dict() for i in range(n): s1, s2 = [i for i in input().split()] pr = a if s1 == pred: pr = b if (s1, s2) in d.keys(): d[(s1, s2)] += pr elif (s2, s1) in d.keys(): d[(s2, s1)] += pr else: d[(s1, s2)] = pr pred = s2 cn = k ans = sum(d.values()) for i in sorted(d.values(), reverse = True): if cn == 0 or i <= f: break ans = ans - i + f cn -= 1 print(ans) ```
output
1
47,601
24
95,203
Provide tags and a correct Python 3 solution for this coding contest problem. In the evening Polycarp decided to analyze his today's travel expenses on public transport. The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops. Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes. It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment. For example, if Polycarp made three consecutive trips: "BerBank" <image> "University", "University" <image> "BerMall", "University" <image> "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus. Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction. What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards? Input The first line contains five integers n, a, b, k, f (1 ≀ n ≀ 300, 1 ≀ b < a ≀ 100, 0 ≀ k ≀ 300, 1 ≀ f ≀ 1000) where: * n β€” the number of Polycarp trips, * a β€” the cost of a regualar single trip, * b β€” the cost of a trip after a transshipment, * k β€” the maximum number of travel cards Polycarp can buy, * f β€” the cost of a single travel card. The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space β€” the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different. Output Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards. Examples Input 3 5 3 1 8 BerBank University University BerMall University BerBank Output 11 Input 4 2 1 300 1000 a A A aa aa AA AA a Output 5 Note In the first example Polycarp can buy travel card for the route "BerBank <image> University" and spend 8 burles. Note that his second trip "University" <image> "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles. In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles.
instruction
0
47,602
24
95,204
Tags: greedy, implementation, sortings Correct Solution: ``` n, a, b, k, f = [int(i) for i in input().split()] stops = dict() prev = "" ans = 0 for i in range(n): x, y = [i for i in input().split()] price = a if x == prev: price = b prev = y p, q = (min(x,y), max(x,y)) if (p, q) in stops: stops[(p,q)] += price else: stops[(p,q)] = price ans += price edge_cost = sorted([stops[key] for key in stops], reverse = True) for i in edge_cost: if k > 0 and f < i: ans = ans - i + f else: break k -= 1 print(ans) ```
output
1
47,602
24
95,205
Provide tags and a correct Python 3 solution for this coding contest problem. In the evening Polycarp decided to analyze his today's travel expenses on public transport. The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops. Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes. It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment. For example, if Polycarp made three consecutive trips: "BerBank" <image> "University", "University" <image> "BerMall", "University" <image> "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus. Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction. What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards? Input The first line contains five integers n, a, b, k, f (1 ≀ n ≀ 300, 1 ≀ b < a ≀ 100, 0 ≀ k ≀ 300, 1 ≀ f ≀ 1000) where: * n β€” the number of Polycarp trips, * a β€” the cost of a regualar single trip, * b β€” the cost of a trip after a transshipment, * k β€” the maximum number of travel cards Polycarp can buy, * f β€” the cost of a single travel card. The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space β€” the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different. Output Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards. Examples Input 3 5 3 1 8 BerBank University University BerMall University BerBank Output 11 Input 4 2 1 300 1000 a A A aa aa AA AA a Output 5 Note In the first example Polycarp can buy travel card for the route "BerBank <image> University" and spend 8 burles. Note that his second trip "University" <image> "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles. In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles.
instruction
0
47,603
24
95,206
Tags: greedy, implementation, sortings Correct Solution: ``` import heapq import sys num_trips, a, b, k, f = sys.stdin.readline().strip().split(" ") a, b, k, f = int(a), int(b), int(k), int(f) #print(a, b, k, f) trips = [] for line in sys.stdin: trips.append(line.strip().split(" ")) """ a = 5 b = 3 k = 1 f = 8 trips = [["BerBank", "University"], ["University", "BerMall"], ["University", "BerBank"], ["University", "BerBank"]] """ my_dict = dict() for i in range(0, len(trips)): trip = trips[i] cost = 0 if(i - 1 >= 0 and trips[i - 1][1] == trip[0]): cost = b; else: cost = a if (str(sorted(trip)) in my_dict): my_dict[str(sorted(trip))] += cost else: my_dict[str(sorted(trip))] = cost heap = [(-1 * my_dict[x], x) for x in my_dict] heapq.heapify(heap) #print(heap) total = sum(int(my_dict[x]) for x in my_dict) for i in range(0, k): if(len(heap) > 0): cur_max = int(heapq.heappop(heap)[0]) * -1 if (cur_max > f): total = total - (cur_max - f) print(total) ```
output
1
47,603
24
95,207
Provide tags and a correct Python 3 solution for this coding contest problem. In the evening Polycarp decided to analyze his today's travel expenses on public transport. The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops. Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes. It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment. For example, if Polycarp made three consecutive trips: "BerBank" <image> "University", "University" <image> "BerMall", "University" <image> "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus. Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction. What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards? Input The first line contains five integers n, a, b, k, f (1 ≀ n ≀ 300, 1 ≀ b < a ≀ 100, 0 ≀ k ≀ 300, 1 ≀ f ≀ 1000) where: * n β€” the number of Polycarp trips, * a β€” the cost of a regualar single trip, * b β€” the cost of a trip after a transshipment, * k β€” the maximum number of travel cards Polycarp can buy, * f β€” the cost of a single travel card. The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space β€” the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different. Output Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards. Examples Input 3 5 3 1 8 BerBank University University BerMall University BerBank Output 11 Input 4 2 1 300 1000 a A A aa aa AA AA a Output 5 Note In the first example Polycarp can buy travel card for the route "BerBank <image> University" and spend 8 burles. Note that his second trip "University" <image> "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles. In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles.
instruction
0
47,604
24
95,208
Tags: greedy, implementation, sortings Correct Solution: ``` def main(): trips, reg, cheap, cards, card_cost = map(int, input().split()) costs = [] indexes = {} total = 0 last = "" for i in range(trips): a, b = input().split() pair = (min(a, b), max(a, b)) if pair in indexes: index = indexes[pair] else: costs.append(0) indexes[pair] = len(costs) - 1 index = len(costs) - 1 total += (cheap if a == last else reg) costs[index] += (cheap if a == last else reg) last = b costs = sorted(costs, reverse = True) for c in costs: if c < card_cost or cards <= 0: break total -= c total += card_cost cards -= 1 print(total) main() ```
output
1
47,604
24
95,209
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the evening Polycarp decided to analyze his today's travel expenses on public transport. The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops. Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes. It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment. For example, if Polycarp made three consecutive trips: "BerBank" <image> "University", "University" <image> "BerMall", "University" <image> "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus. Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction. What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards? Input The first line contains five integers n, a, b, k, f (1 ≀ n ≀ 300, 1 ≀ b < a ≀ 100, 0 ≀ k ≀ 300, 1 ≀ f ≀ 1000) where: * n β€” the number of Polycarp trips, * a β€” the cost of a regualar single trip, * b β€” the cost of a trip after a transshipment, * k β€” the maximum number of travel cards Polycarp can buy, * f β€” the cost of a single travel card. The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space β€” the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different. Output Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards. Examples Input 3 5 3 1 8 BerBank University University BerMall University BerBank Output 11 Input 4 2 1 300 1000 a A A aa aa AA AA a Output 5 Note In the first example Polycarp can buy travel card for the route "BerBank <image> University" and spend 8 burles. Note that his second trip "University" <image> "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles. In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles. Submitted Solution: ``` import heapq import sys num_trips, a, b, k, f = sys.stdin.readline().strip().split(" ") a, b, k, f = int(a), int(b), int(k), int(f) #print(a, b, k, f) trips = [] for line in sys.stdin: trips.append(line.strip().split(" ")) """ a = 5 b = 3 k = 1 f = 8 trips = [["BerBank", "University"], ["University", "BerMall"], ["University", "BerBank"]] """ my_dict = dict() for i in range(0, len(trips)): trip = trips[i] cost = 0 if(i - 1 >= 0 and trips[i - 1][1] == trip[0]): cost = b; else: cost = a if (str(sorted(trip)) in my_dict): my_dict[str(sorted(trip))] += cost else: my_dict[str(sorted(trip))] = cost heap = [(my_dict[x], x) for x in my_dict] heapq._heapify_max(heap) #print(heap) total = sum(int(my_dict[x]) for x in my_dict) for i in range(0, k): if(len(heap) > 0): cur_max = int(heapq.heappop(heap)[0]) if (cur_max > f): total = total - (cur_max - f) print(total) ```
instruction
0
47,605
24
95,210
No
output
1
47,605
24
95,211
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...
instruction
0
48,167
24
96,334
Tags: *special, implementation, number theory Correct Solution: ``` ABMR = list(map(int, input().split())) # print(ABMR) a = ABMR[0] b = ABMR[1] m = ABMR[2] r0 = ABMR[3] h = {} i = 0 prev_r = r0 while True: cur_r = ( a * prev_r + b ) % m # print(cur_r) if h.get(cur_r, 0) != 0: print(i - h[cur_r]) break else: h[cur_r] = i prev_r = cur_r i += 1 ```
output
1
48,167
24
96,335
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...
instruction
0
48,168
24
96,336
Tags: *special, implementation, number theory Correct Solution: ``` a, b, m, r0 = map(int, input().split()) numbers = {} counter = 0 period = 0 r = r0 while True: r1 = (a*r + b)%m counter += 1 if r1 in numbers: period = counter - numbers[r1] break else: numbers[r1] = counter r = r1 print(period) ```
output
1
48,168
24
96,337
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...
instruction
0
48,169
24
96,338
Tags: *special, implementation, number theory Correct Solution: ``` def STR(): return list(input()) def INT(): return int(input()) def MAP(): return map(int, input().split()) def MAP2():return map(float,input().split()) def LIST(): return list(map(int, input().split())) def STRING(): return input() import string import sys import datetime from heapq import heappop , heappush from bisect import * from collections import deque , Counter , defaultdict from math import * from itertools import permutations , accumulate dx = [-1 , 1 , 0 , 0 ] dy = [0 , 0 , 1 , - 1] #visited = [[False for i in range(m)] for j in range(n)] # primes = [2,11,101,1009,10007,100003,1000003,10000019,102345689] #months = [31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31, 30 , 31] #sys.stdin = open(r'input.txt' , 'r') #sys.stdout = open(r'output.txt' , 'w') #for tt in range(INT()): #arr.sort(key=lambda x: (-d[x], x)) Sort with Freq #Code def solve(a , b , m , r): k = ( ((a * r) % m) + (b % m )) % m return k a , b , m , r = MAP() d = {} ans = 0 i = 1 while True: k = (solve(a , b , m , r)) r = k x = d.get(k , 0) if x != 0 : ans = i - x break else: d[k] = i i +=1 print(ans) ```
output
1
48,169
24
96,339
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...
instruction
0
48,170
24
96,340
Tags: *special, implementation, number theory Correct Solution: ``` def rand(a, b, m, r): return (a * r + b) % m class CodeforcesTask172BSolution: def __init__(self): self.result = '' self.a_b_m_r = [] def read_input(self): self.a_b_m_r = [int(x) for x in input().split(" ")] def process_task(self): sequence = [rand(*self.a_b_m_r)] for x in range(100000): sequence.append(rand(self.a_b_m_r[0], self.a_b_m_r[1], self.a_b_m_r[2], sequence[-1])) freq = [] counts = [0 for x in range(max(sequence) + 1)] for s in sequence: counts[s] += 1 #print(sequence) for x in list(set(sequence)): freq.append((x, round(10000 * (counts[x] / len(sequence))))) #print(freq) cycle = 0 cycle_r = max([x[1] for x in freq]) for f in freq: #print(f) if abs(f[1] - cycle_r) <= 2: cycle += 1 #print(cycle_r) self.result = str(cycle) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask172BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
output
1
48,170
24
96,341
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...
instruction
0
48,171
24
96,342
Tags: *special, implementation, number theory Correct Solution: ``` a,b,m,r=map(int,input().split()) l,s=[],set() while r not in s: s.add(r) l.append(r) r=(a*r + b)%m print(len(l)-l.index(r)) ```
output
1
48,171
24
96,343
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...
instruction
0
48,172
24
96,344
Tags: *special, implementation, number theory Correct Solution: ``` import sys a, b, m, x = tuple(map(int, input().split())) z=[0]*(m+1) cnt=1 z[x]=cnt while True: cnt += 1 x = (x*a+b)%m if z[x] > 0: print(str(cnt-z[x])) sys.exit(0) z[x] = cnt ```
output
1
48,172
24
96,345
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...
instruction
0
48,173
24
96,346
Tags: *special, implementation, number theory Correct Solution: ``` a, b, m, r0 = [int(k) for k in input().split(' ') if k] valueToPos = [-1 for _ in range(m + 1)] prev = r0 for i in range(m + 1): prev = (a * prev + b) % m if valueToPos[prev] != -1: print(i - valueToPos[prev]) exit() valueToPos[prev] = i raise Exception ```
output
1
48,173
24
96,347
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...
instruction
0
48,174
24
96,348
Tags: *special, implementation, number theory Correct Solution: ``` import re import itertools from collections import Counter, deque class Task: a, b, m, r = 0, 0, 0, 0 answer = 0 def getData(self): self.a, self.b, self.m, self.r = [int(x) for x in input().split(' ')] #inFile = open('input.txt', 'r') #inFile.readline().rstrip() #self.childs = inFile.readline().rstrip() def solve(self): a, b, m, r = self.a, self.b, self.m, self.r occurrences = dict({r : 0}) iterationCounter = 1 while True: r = (a * r + b) % m if r in occurrences: self.answer = iterationCounter - occurrences[r] return occurrences[r] = iterationCounter iterationCounter += 1 def printAnswer(self): print(self.answer) #outFile = open('output.txt', 'w') #outFile.write(self.answer) task = Task() task.getData() task.solve() task.printAnswer() ```
output
1
48,174
24
96,349
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ... Submitted Solution: ``` a,b,m,r0=0,0,0,0 a,b,m,r0=map(int,input().split()) ri=r0 i=0 I={} while (ri) not in I: I[ri]=i ri=(a*ri+b)%m i+=1 print (i-I[ri]) ```
instruction
0
48,175
24
96,350
Yes
output
1
48,175
24
96,351
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ... Submitted Solution: ``` a,b,m,r0=map(int,input().split()) dct={} i=0 while(True): r0=(a*r0+b)%m i+=1 if(r0 not in dct.keys()): dct[r0]=i else: print(i-dct[r0]) break ```
instruction
0
48,176
24
96,352
Yes
output
1
48,176
24
96,353
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ... Submitted Solution: ``` a,b,m,r=map(int,input().split()) d={} i=1 while 1: r=(a*r+b)%m;t=d.get(r,0) if t:i-=t;break d[r]=i;i+=1 print() print(i) ```
instruction
0
48,177
24
96,354
Yes
output
1
48,177
24
96,355
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division. For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, .... Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2. Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t. Input The single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces. Output Print a single integer β€” the period of the sequence. Examples Input 2 6 12 11 Output 2 Input 2 3 5 1 Output 4 Input 3 6 81 9 Output 1 Note The first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ... In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ... Submitted Solution: ``` a,b,m,r0=0,0,0,0 a,b,m,r0=map(int,input().split()) ri=r0 i=0 I={} while (ri) not in I: I[ri]=i ri=(a*ri+b)%m i+=1 print (i-I[ri]) # Made By Mostafa_Khaled ```
instruction
0
48,178
24
96,356
Yes
output
1
48,178
24
96,357