text stringlengths 1.02k 43.5k | conversation_id int64 853 107k | embedding list | cluster int64 24 24 |
|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
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
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 )
```
| 46,312 | [
0.48876953125,
0.0220184326171875,
0.08258056640625,
-0.04473876953125,
-0.5849609375,
-0.67333984375,
-0.30419921875,
0.0665283203125,
0.10003662109375,
0.52001953125,
0.92919921875,
-0.153076171875,
0.44580078125,
-0.642578125,
-0.341796875,
0.1187744140625,
-0.6845703125,
-0.725... | 24 |
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
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()))
```
| 46,313 | [
0.462890625,
0.033538818359375,
0.086669921875,
-0.061431884765625,
-0.57470703125,
-0.736328125,
-0.431396484375,
0.09149169921875,
0.061614990234375,
0.521484375,
0.91259765625,
-0.1541748046875,
0.47998046875,
-0.60791015625,
-0.363525390625,
0.0672607421875,
-0.654296875,
-0.79... | 24 |
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
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()
```
| 46,314 | [
0.498046875,
0.07470703125,
0.069580078125,
-0.041290283203125,
-0.52880859375,
-0.7587890625,
-0.4140625,
0.0899658203125,
0.054840087890625,
0.495849609375,
0.9501953125,
-0.196533203125,
0.436279296875,
-0.63427734375,
-0.329833984375,
0.10205078125,
-0.6904296875,
-0.728515625,... | 24 |
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
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)
```
| 46,315 | [
0.494140625,
0.048248291015625,
0.12469482421875,
-0.038421630859375,
-0.57763671875,
-0.7001953125,
-0.3583984375,
0.0950927734375,
0.0755615234375,
0.5234375,
0.91259765625,
-0.17333984375,
0.48291015625,
-0.6494140625,
-0.38818359375,
0.0740966796875,
-0.6845703125,
-0.769042968... | 24 |
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
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]))
```
| 46,316 | [
0.5126953125,
0.04034423828125,
0.020050048828125,
-0.0845947265625,
-0.56591796875,
-0.6953125,
-0.289794921875,
0.0521240234375,
0.08685302734375,
0.4765625,
0.96435546875,
-0.1319580078125,
0.47802734375,
-0.69189453125,
-0.364013671875,
0.0080718994140625,
-0.6826171875,
-0.708... | 24 |
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
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
```
| 46,317 | [
0.5029296875,
0.04400634765625,
0.053497314453125,
-0.0032596588134765625,
-0.5283203125,
-0.72412109375,
-0.325927734375,
0.09112548828125,
0.08056640625,
0.501953125,
0.91748046875,
-0.1474609375,
0.501953125,
-0.64404296875,
-0.367431640625,
0.05316162109375,
-0.69189453125,
-0.... | 24 |
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
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)
```
| 46,318 | [
0.505859375,
0.03155517578125,
0.0740966796875,
-0.004108428955078125,
-0.54931640625,
-0.71435546875,
-0.319580078125,
0.11724853515625,
0.06610107421875,
0.55322265625,
0.9521484375,
-0.1605224609375,
0.462890625,
-0.67724609375,
-0.358642578125,
0.06121826171875,
-0.6953125,
-0.... | 24 |
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()
```
Yes
| 46,319 | [
0.541015625,
0.2069091796875,
0.03277587890625,
-0.126220703125,
-0.68017578125,
-0.5,
-0.38525390625,
0.1890869140625,
0.00775909423828125,
0.583984375,
0.98486328125,
-0.08685302734375,
0.45361328125,
-0.73388671875,
-0.390380859375,
0.04693603515625,
-0.7099609375,
-0.6806640625... | 24 |
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)
```
Yes
| 46,320 | [
0.57373046875,
0.1392822265625,
0.034820556640625,
-0.0848388671875,
-0.63916015625,
-0.57568359375,
-0.364013671875,
0.19140625,
0.0026149749755859375,
0.58984375,
1.0068359375,
-0.06494140625,
0.474365234375,
-0.7109375,
-0.35546875,
0.06378173828125,
-0.70068359375,
-0.634277343... | 24 |
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)
```
Yes
| 46,321 | [
0.5361328125,
0.193359375,
0.07025146484375,
-0.086181640625,
-0.6796875,
-0.50537109375,
-0.375244140625,
0.17431640625,
-0.031341552734375,
0.59765625,
0.978515625,
-0.0894775390625,
0.45654296875,
-0.712890625,
-0.3701171875,
0.0684814453125,
-0.69921875,
-0.67138671875,
-0.63... | 24 |
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)]))
```
Yes
| 46,322 | [
0.501953125,
0.205078125,
0.050750732421875,
-0.05279541015625,
-0.73388671875,
-0.548828125,
-0.32470703125,
0.1295166015625,
-0.0030574798583984375,
0.64697265625,
0.99169921875,
-0.04656982421875,
0.458740234375,
-0.810546875,
-0.391845703125,
0.0528564453125,
-0.71875,
-0.74658... | 24 |
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)
```
No
| 46,323 | [
0.57373046875,
0.1392822265625,
0.034820556640625,
-0.0848388671875,
-0.63916015625,
-0.57568359375,
-0.364013671875,
0.19140625,
0.0026149749755859375,
0.58984375,
1.0068359375,
-0.06494140625,
0.474365234375,
-0.7109375,
-0.35546875,
0.06378173828125,
-0.70068359375,
-0.634277343... | 24 |
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)
```
No
| 46,324 | [
0.501953125,
0.205078125,
0.050750732421875,
-0.05279541015625,
-0.73388671875,
-0.548828125,
-0.32470703125,
0.1295166015625,
-0.0030574798583984375,
0.64697265625,
0.99169921875,
-0.04656982421875,
0.458740234375,
-0.810546875,
-0.391845703125,
0.0528564453125,
-0.71875,
-0.74658... | 24 |
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)
```
No
| 46,325 | [
0.57568359375,
0.137451171875,
0.035430908203125,
-0.0845947265625,
-0.63134765625,
-0.57763671875,
-0.366943359375,
0.1905517578125,
0.0028247833251953125,
0.58984375,
0.9921875,
-0.0673828125,
0.47119140625,
-0.7109375,
-0.352294921875,
0.06561279296875,
-0.69384765625,
-0.638671... | 24 |
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)
```
No
| 46,326 | [
0.54150390625,
0.17626953125,
0.0699462890625,
-0.0958251953125,
-0.68408203125,
-0.52294921875,
-0.37939453125,
0.1934814453125,
-0.00698089599609375,
0.58544921875,
0.95654296875,
-0.08587646484375,
0.469970703125,
-0.72998046875,
-0.3828125,
0.06500244140625,
-0.70068359375,
-0.... | 24 |
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.
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()
```
| 46,657 | [
0.576171875,
0.2430419921875,
0.430908203125,
0.2166748046875,
-0.35888671875,
-0.08465576171875,
-0.52685546875,
0.18505859375,
0.4150390625,
0.8876953125,
0.3291015625,
-0.159423828125,
-0.11700439453125,
-1.123046875,
-0.720703125,
0.2001953125,
-0.92822265625,
-0.82666015625,
... | 24 |
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.
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]))
```
| 46,658 | [
0.5634765625,
0.264404296875,
0.421142578125,
0.206787109375,
-0.359375,
-0.109619140625,
-0.501953125,
0.1876220703125,
0.383056640625,
0.9052734375,
0.347412109375,
-0.132568359375,
-0.1583251953125,
-1.1171875,
-0.68408203125,
0.228515625,
-0.9013671875,
-0.8232421875,
-0.6582... | 24 |
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.
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)
```
| 46,659 | [
0.5810546875,
0.23291015625,
0.38623046875,
0.199951171875,
-0.3681640625,
-0.12066650390625,
-0.5146484375,
0.1812744140625,
0.375732421875,
0.88916015625,
0.33251953125,
-0.1778564453125,
-0.10125732421875,
-1.091796875,
-0.6982421875,
0.1319580078125,
-0.9287109375,
-0.80859375,... | 24 |
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.
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)
```
| 46,660 | [
0.5634765625,
0.2301025390625,
0.37939453125,
0.20654296875,
-0.38671875,
-0.060455322265625,
-0.5087890625,
0.1680908203125,
0.41162109375,
0.8759765625,
0.31298828125,
-0.1788330078125,
-0.11053466796875,
-1.0771484375,
-0.69482421875,
0.1611328125,
-0.9267578125,
-0.84423828125,... | 24 |
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.
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" )
```
| 46,661 | [
0.57861328125,
0.2384033203125,
0.427978515625,
0.223876953125,
-0.369384765625,
-0.1248779296875,
-0.52099609375,
0.188232421875,
0.39990234375,
0.87841796875,
0.34326171875,
-0.153076171875,
-0.1270751953125,
-1.11328125,
-0.69287109375,
0.18359375,
-0.90478515625,
-0.83740234375... | 24 |
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.
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)
```
| 46,662 | [
0.56201171875,
0.23876953125,
0.407958984375,
0.211669921875,
-0.371826171875,
-0.11083984375,
-0.515625,
0.1839599609375,
0.385498046875,
0.9033203125,
0.340576171875,
-0.1612548828125,
-0.1092529296875,
-1.1005859375,
-0.68603515625,
0.203369140625,
-0.92529296875,
-0.828125,
-... | 24 |
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.
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))
```
| 46,663 | [
0.5830078125,
0.24462890625,
0.410888671875,
0.2322998046875,
-0.342529296875,
-0.109619140625,
-0.5302734375,
0.1795654296875,
0.3798828125,
0.89892578125,
0.349365234375,
-0.1456298828125,
-0.1170654296875,
-1.1025390625,
-0.68603515625,
0.2064208984375,
-0.9140625,
-0.8076171875... | 24 |
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.
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)
```
| 46,664 | [
0.53173828125,
0.2427978515625,
0.3984375,
0.162109375,
-0.414794921875,
-0.11553955078125,
-0.6025390625,
0.1337890625,
0.383056640625,
0.8798828125,
0.268798828125,
-0.1488037109375,
-0.1375732421875,
-1.1025390625,
-0.69091796875,
0.1962890625,
-0.90869140625,
-0.83349609375,
... | 24 |
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()
```
Yes
| 46,665 | [
0.623046875,
0.293212890625,
0.3310546875,
0.2445068359375,
-0.50927734375,
-0.019073486328125,
-0.56689453125,
0.234130859375,
0.385009765625,
0.91796875,
0.341552734375,
-0.123779296875,
-0.1025390625,
-1.0869140625,
-0.62158203125,
0.196533203125,
-0.78955078125,
-0.90869140625,... | 24 |
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()
```
Yes
| 46,666 | [
0.55517578125,
0.263916015625,
0.2469482421875,
0.265869140625,
-0.5205078125,
-0.00954437255859375,
-0.5029296875,
0.2003173828125,
0.3837890625,
0.96484375,
0.256591796875,
-0.127685546875,
-0.0361328125,
-1.0458984375,
-0.640625,
0.1644287109375,
-0.8271484375,
-0.966796875,
-... | 24 |
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)
```
Yes
| 46,667 | [
0.6123046875,
0.272705078125,
0.33447265625,
0.2269287109375,
-0.490966796875,
-0.0288543701171875,
-0.52099609375,
0.2469482421875,
0.387451171875,
0.94921875,
0.385498046875,
-0.10565185546875,
-0.09503173828125,
-1.130859375,
-0.64501953125,
0.193115234375,
-0.79638671875,
-0.92... | 24 |
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)
```
Yes
| 46,668 | [
0.625,
0.315673828125,
0.32666015625,
0.22412109375,
-0.446044921875,
-0.0281829833984375,
-0.5771484375,
0.272216796875,
0.400390625,
0.93017578125,
0.411865234375,
-0.0633544921875,
-0.1243896484375,
-1.12890625,
-0.6064453125,
0.2381591796875,
-0.74853515625,
-0.92919921875,
-... | 24 |
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)
```
No
| 46,669 | [
0.6083984375,
0.28564453125,
0.290771484375,
0.186279296875,
-0.47265625,
-0.02056884765625,
-0.51220703125,
0.2432861328125,
0.419677734375,
0.8984375,
0.393798828125,
-0.1265869140625,
-0.03759765625,
-1.134765625,
-0.65576171875,
0.15185546875,
-0.78759765625,
-0.87255859375,
... | 24 |
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))
```
No
| 46,670 | [
0.619140625,
0.2900390625,
0.357666015625,
0.2200927734375,
-0.453857421875,
-0.006824493408203125,
-0.5244140625,
0.306884765625,
0.42578125,
0.90380859375,
0.3759765625,
-0.1134033203125,
-0.1004638671875,
-1.1298828125,
-0.64306640625,
0.234130859375,
-0.7919921875,
-0.854980468... | 24 |
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)
```
No
| 46,671 | [
0.63427734375,
0.308837890625,
0.34130859375,
0.1943359375,
-0.443115234375,
-0.0300140380859375,
-0.55224609375,
0.29150390625,
0.369140625,
0.96044921875,
0.382568359375,
-0.06951904296875,
-0.1226806640625,
-1.1201171875,
-0.61328125,
0.2198486328125,
-0.75830078125,
-0.88964843... | 24 |
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)
```
No
| 46,672 | [
0.61865234375,
0.27490234375,
0.31640625,
0.1934814453125,
-0.483154296875,
-0.062042236328125,
-0.58251953125,
0.2489013671875,
0.395263671875,
0.900390625,
0.352294921875,
-0.1268310546875,
-0.09234619140625,
-1.1142578125,
-0.64599609375,
0.1885986328125,
-0.80712890625,
-0.8598... | 24 |
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.
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))
```
| 47,599 | [
0.2235107421875,
0.0633544921875,
0.2783203125,
0.068603515625,
-0.265869140625,
-0.414794921875,
-0.11358642578125,
0.08123779296875,
-0.03973388671875,
0.83544921875,
0.74951171875,
0.055999755859375,
0.3310546875,
-0.81640625,
-0.95751953125,
0.0821533203125,
-0.5546875,
-0.5634... | 24 |
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.
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)
```
| 47,600 | [
0.2235107421875,
0.0633544921875,
0.2783203125,
0.068603515625,
-0.265869140625,
-0.414794921875,
-0.11358642578125,
0.08123779296875,
-0.03973388671875,
0.83544921875,
0.74951171875,
0.055999755859375,
0.3310546875,
-0.81640625,
-0.95751953125,
0.0821533203125,
-0.5546875,
-0.5634... | 24 |
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.
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)
```
| 47,601 | [
0.2235107421875,
0.0633544921875,
0.2783203125,
0.068603515625,
-0.265869140625,
-0.414794921875,
-0.11358642578125,
0.08123779296875,
-0.03973388671875,
0.83544921875,
0.74951171875,
0.055999755859375,
0.3310546875,
-0.81640625,
-0.95751953125,
0.0821533203125,
-0.5546875,
-0.5634... | 24 |
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.
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)
```
| 47,602 | [
0.2235107421875,
0.0633544921875,
0.2783203125,
0.068603515625,
-0.265869140625,
-0.414794921875,
-0.11358642578125,
0.08123779296875,
-0.03973388671875,
0.83544921875,
0.74951171875,
0.055999755859375,
0.3310546875,
-0.81640625,
-0.95751953125,
0.0821533203125,
-0.5546875,
-0.5634... | 24 |
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.
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)
```
| 47,603 | [
0.2235107421875,
0.0633544921875,
0.2783203125,
0.068603515625,
-0.265869140625,
-0.414794921875,
-0.11358642578125,
0.08123779296875,
-0.03973388671875,
0.83544921875,
0.74951171875,
0.055999755859375,
0.3310546875,
-0.81640625,
-0.95751953125,
0.0821533203125,
-0.5546875,
-0.5634... | 24 |
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.
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()
```
| 47,604 | [
0.2235107421875,
0.0633544921875,
0.2783203125,
0.068603515625,
-0.265869140625,
-0.414794921875,
-0.11358642578125,
0.08123779296875,
-0.03973388671875,
0.83544921875,
0.74951171875,
0.055999755859375,
0.3310546875,
-0.81640625,
-0.95751953125,
0.0821533203125,
-0.5546875,
-0.5634... | 24 |
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)
```
No
| 47,605 | [
0.293701171875,
0.1900634765625,
0.340087890625,
0.0875244140625,
-0.31396484375,
-0.30322265625,
-0.1494140625,
0.1282958984375,
-0.060516357421875,
0.90478515625,
0.6591796875,
0.08868408203125,
0.3203125,
-0.767578125,
-0.90185546875,
0.06072998046875,
-0.53271484375,
-0.5346679... | 24 |
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, ...
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
```
| 48,167 | [
0.51708984375,
0.2861328125,
0.1751708984375,
-0.4853515625,
-0.10589599609375,
-0.34521484375,
-0.385009765625,
0.0943603515625,
-0.039306640625,
0.8154296875,
0.71435546875,
-0.65869140625,
0.32421875,
-0.63427734375,
-0.46923828125,
0.291748046875,
-0.6572265625,
-0.580078125,
... | 24 |
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, ...
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)
```
| 48,168 | [
0.457275390625,
0.2734375,
0.1729736328125,
-0.46630859375,
-0.11663818359375,
-0.37109375,
-0.386962890625,
0.1094970703125,
-0.045745849609375,
0.8203125,
0.72900390625,
-0.59619140625,
0.359130859375,
-0.6064453125,
-0.460205078125,
0.345703125,
-0.66796875,
-0.55029296875,
-0... | 24 |
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, ...
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)
```
| 48,169 | [
0.46923828125,
0.271484375,
0.162841796875,
-0.47998046875,
-0.1287841796875,
-0.31689453125,
-0.385498046875,
0.11614990234375,
-0.0361328125,
0.80126953125,
0.7294921875,
-0.62353515625,
0.35791015625,
-0.60205078125,
-0.43798828125,
0.37890625,
-0.68603515625,
-0.55126953125,
... | 24 |
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, ...
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())
```
| 48,170 | [
0.460205078125,
0.28369140625,
0.197265625,
-0.42578125,
-0.12646484375,
-0.353515625,
-0.37255859375,
0.0736083984375,
-0.048431396484375,
0.7900390625,
0.74560546875,
-0.6298828125,
0.3505859375,
-0.5927734375,
-0.413818359375,
0.356201171875,
-0.67138671875,
-0.5390625,
-0.541... | 24 |
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, ...
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))
```
| 48,171 | [
0.451171875,
0.2734375,
0.187255859375,
-0.488037109375,
-0.11370849609375,
-0.326904296875,
-0.38427734375,
0.09393310546875,
-0.0311431884765625,
0.7841796875,
0.755859375,
-0.6298828125,
0.359375,
-0.615234375,
-0.4560546875,
0.36181640625,
-0.69482421875,
-0.54150390625,
-0.5... | 24 |
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, ...
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
```
| 48,172 | [
0.462890625,
0.26904296875,
0.18798828125,
-0.47802734375,
-0.1390380859375,
-0.38134765625,
-0.41015625,
0.0775146484375,
-0.042510986328125,
0.84619140625,
0.71484375,
-0.5654296875,
0.35205078125,
-0.59814453125,
-0.471923828125,
0.37744140625,
-0.6689453125,
-0.568359375,
-0.... | 24 |
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, ...
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
```
| 48,173 | [
0.436279296875,
0.29541015625,
0.217041015625,
-0.4326171875,
-0.11151123046875,
-0.365234375,
-0.384765625,
0.09869384765625,
-0.0204620361328125,
0.7880859375,
0.71484375,
-0.60791015625,
0.35302734375,
-0.59423828125,
-0.458740234375,
0.35888671875,
-0.65234375,
-0.54248046875,
... | 24 |
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, ...
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()
```
| 48,174 | [
0.45849609375,
0.251953125,
0.1844482421875,
-0.45263671875,
-0.12127685546875,
-0.3056640625,
-0.375244140625,
0.058441162109375,
-0.03564453125,
0.8076171875,
0.73583984375,
-0.63818359375,
0.338134765625,
-0.599609375,
-0.484619140625,
0.369140625,
-0.6845703125,
-0.52978515625,... | 24 |
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])
```
Yes
| 48,175 | [
0.447509765625,
0.31982421875,
0.142333984375,
-0.404296875,
-0.298095703125,
-0.2001953125,
-0.499267578125,
0.1776123046875,
-0.043243408203125,
0.82861328125,
0.765625,
-0.60205078125,
0.28125,
-0.732421875,
-0.46337890625,
0.382568359375,
-0.7001953125,
-0.66259765625,
-0.480... | 24 |
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
```
Yes
| 48,176 | [
0.45166015625,
0.30078125,
0.1707763671875,
-0.401123046875,
-0.261474609375,
-0.213134765625,
-0.50537109375,
0.1824951171875,
-0.051513671875,
0.8466796875,
0.7392578125,
-0.6220703125,
0.3095703125,
-0.73876953125,
-0.4990234375,
0.37841796875,
-0.703125,
-0.65087890625,
-0.49... | 24 |
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)
```
Yes
| 48,177 | [
0.452880859375,
0.3095703125,
0.1600341796875,
-0.4033203125,
-0.2841796875,
-0.2010498046875,
-0.491943359375,
0.183349609375,
-0.040863037109375,
0.81689453125,
0.75537109375,
-0.64013671875,
0.2802734375,
-0.7255859375,
-0.49365234375,
0.368896484375,
-0.70751953125,
-0.65673828... | 24 |
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
```
Yes
| 48,178 | [
0.447509765625,
0.31982421875,
0.142333984375,
-0.404296875,
-0.298095703125,
-0.2001953125,
-0.499267578125,
0.1776123046875,
-0.043243408203125,
0.82861328125,
0.765625,
-0.60205078125,
0.28125,
-0.732421875,
-0.46337890625,
0.382568359375,
-0.7001953125,
-0.66259765625,
-0.480... | 24 |
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:
```
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
```
No
| 48,179 | [
0.51904296875,
0.302001953125,
0.1434326171875,
-0.41943359375,
-0.28466796875,
-0.18505859375,
-0.476318359375,
0.1522216796875,
-0.02459716796875,
0.83740234375,
0.75341796875,
-0.68505859375,
0.26123046875,
-0.74951171875,
-0.4970703125,
0.330322265625,
-0.70068359375,
-0.662109... | 24 |
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())
l=list()
temp=r
l.append(temp)
flag=0
p=0
for i in range(100):
temp = (a*temp+b)%m
for j in range(len(l)):
if l[j]==temp:
flag=1
p=j
break
if flag==1:
print(len(l)-p)
break
else:
l.append(temp)
```
No
| 48,180 | [
0.46044921875,
0.2880859375,
0.1583251953125,
-0.380859375,
-0.293701171875,
-0.206787109375,
-0.493408203125,
0.1915283203125,
-0.03424072265625,
0.84130859375,
0.7607421875,
-0.63623046875,
0.283935546875,
-0.72412109375,
-0.482421875,
0.368896484375,
-0.6943359375,
-0.6733398437... | 24 |
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())
ss=[]
l=r
start=0
cnt=(10**3)+1
while cnt:
s=(a*l+b)%m
l=s
ss.append(l)
cnt-=1
cnt=0
s=set(ss)
for i in s:
if ss.count(i)>1:
cnt+=1
print(cnt)
```
No
| 48,181 | [
0.441650390625,
0.305419921875,
0.152099609375,
-0.398193359375,
-0.26416015625,
-0.201416015625,
-0.486083984375,
0.1798095703125,
-0.02886962890625,
0.83837890625,
0.75341796875,
-0.62158203125,
0.264892578125,
-0.73388671875,
-0.501953125,
0.372802734375,
-0.71875,
-0.6684570312... | 24 |
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:
```
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 = {}
for i in range(10**5 + 1):
k = (solve(a , b , m , r))
d[k] = d.get(k , 0) + 1
r = k
#print(d)
cnt = 0
for i in d :
if d[i] > 1 :
cnt +=1
print(cnt)
```
No
| 48,182 | [
0.486328125,
0.306396484375,
0.125732421875,
-0.4326171875,
-0.28515625,
-0.1767578125,
-0.484619140625,
0.18603515625,
-0.038177490234375,
0.82373046875,
0.75732421875,
-0.64453125,
0.303466796875,
-0.71435546875,
-0.476318359375,
0.38427734375,
-0.7236328125,
-0.65087890625,
-0... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.
He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).
Implement this feature to help Polycarp test his editor.
Input
The first line contains two integers, w and h (1 β€ w, h β€ 100) β the width and height of an image in pixels. The picture is given in h lines, each line contains w characters β each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.
Output
Print 2w lines, each containing 2h characters β the result of consecutive implementing of the three transformations, described above.
Examples
Input
3 2
.*.
.*.
Output
....
....
****
****
....
....
Input
9 20
**.......
****.....
******...
*******..
..******.
....****.
......***
*.....***
*********
*********
*********
*********
....**...
...****..
..******.
.********
****..***
***...***
**.....**
*.......*
Output
********......**********........********
********......**********........********
********........********......********..
********........********......********..
..********......********....********....
..********......********....********....
..********......********..********......
..********......********..********......
....********....****************........
....********....****************........
....********....****************........
....********....****************........
......******************..**********....
......******************..**********....
........****************....**********..
........****************....**********..
............************......**********
............************......**********
Tags: *special, implementation
Correct Solution:
```
n,m=map(int,input().split())
array=[]
array1=[]
array2=[]
for i in range(m):
s=input()
array+=[s]
for j in range(n):
s=''
for i in range(m):
s+=array[i][j]
array1+=[s]
array2+=[s]
q=len(array1)
array=[]
for i in range(q):
array+=[array1[i]]
array+=[array2[i]]
array1=[]
for i in range(2*n):
s=''
for j in range(m):
s+=array[i][j]
s+=array[i][j]
array1+=[s]
for i in range(len(array)):
print(array1[i])
```
| 48,318 | [
0.4072265625,
-0.15966796875,
0.031768798828125,
-0.06201171875,
-0.316162109375,
-0.35498046875,
-0.271728515625,
0.3037109375,
0.031402587890625,
0.91162109375,
0.705078125,
-0.221923828125,
0.51025390625,
-0.67626953125,
-0.5185546875,
0.03363037109375,
-0.2423095703125,
-0.7675... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.
He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).
Implement this feature to help Polycarp test his editor.
Input
The first line contains two integers, w and h (1 β€ w, h β€ 100) β the width and height of an image in pixels. The picture is given in h lines, each line contains w characters β each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.
Output
Print 2w lines, each containing 2h characters β the result of consecutive implementing of the three transformations, described above.
Examples
Input
3 2
.*.
.*.
Output
....
....
****
****
....
....
Input
9 20
**.......
****.....
******...
*******..
..******.
....****.
......***
*.....***
*********
*********
*********
*********
....**...
...****..
..******.
.********
****..***
***...***
**.....**
*.......*
Output
********......**********........********
********......**********........********
********........********......********..
********........********......********..
..********......********....********....
..********......********....********....
..********......********..********......
..********......********..********......
....********....****************........
....********....****************........
....********....****************........
....********....****************........
......******************..**********....
......******************..**********....
........****************....**********..
........****************....**********..
............************......**********
............************......**********
Tags: *special, implementation
Correct Solution:
```
s=input()
w=int(s.split()[0])
h=int(s.split()[1])
L=[]
L2=[]
s2=''
for i in(range(h)):
L.append(input())
for i in(range(w)):
for k in(range(h-1,-1,-1)):
s2=s2+L[k][i]
L2.append(s2)
s2=''
L3=[]
s3=''
for i in((range(w))):
for k in((range(h-1,-1,-1))):
s3=s3+L2[i][k]
L3.append(s3)
s3=''
L4=[]
for i in((range(w))):
for k in((range(h))):
s3=s3+((L3[i][k]*2))
L4.append(s3)
L4.append(s3)
s3=''
w2=w*2
for i in (range(w2)):
print(L4[i])
```
| 48,319 | [
0.4072265625,
-0.15966796875,
0.031768798828125,
-0.06201171875,
-0.316162109375,
-0.35498046875,
-0.271728515625,
0.3037109375,
0.031402587890625,
0.91162109375,
0.705078125,
-0.221923828125,
0.51025390625,
-0.67626953125,
-0.5185546875,
0.03363037109375,
-0.2423095703125,
-0.7675... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.
He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).
Implement this feature to help Polycarp test his editor.
Input
The first line contains two integers, w and h (1 β€ w, h β€ 100) β the width and height of an image in pixels. The picture is given in h lines, each line contains w characters β each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.
Output
Print 2w lines, each containing 2h characters β the result of consecutive implementing of the three transformations, described above.
Examples
Input
3 2
.*.
.*.
Output
....
....
****
****
....
....
Input
9 20
**.......
****.....
******...
*******..
..******.
....****.
......***
*.....***
*********
*********
*********
*********
....**...
...****..
..******.
.********
****..***
***...***
**.....**
*.......*
Output
********......**********........********
********......**********........********
********........********......********..
********........********......********..
..********......********....********....
..********......********....********....
..********......********..********......
..********......********..********......
....********....****************........
....********....****************........
....********....****************........
....********....****************........
......******************..**********....
......******************..**********....
........****************....**********..
........****************....**********..
............************......**********
............************......**********
Tags: *special, implementation
Correct Solution:
```
#!/usr/bin/python3
w, h = map(int, input().split())
arr = [list(input()) for i in range(h)]
rotated_and_mirrored = [[arr[i][j] for i in range(h)] for j in range(w)]
ans = [["" for i in range(2 * h)] for j in range(2 * w)]
for i in range(w):
for j in range(h):
for dx in range(2):
for dy in range(2):
ans[2 * i + dx][2 * j + dy] = rotated_and_mirrored[i][j]
print("\n".join(map(lambda x : "".join(x), ans)))
```
| 48,320 | [
0.4072265625,
-0.15966796875,
0.031768798828125,
-0.06201171875,
-0.316162109375,
-0.35498046875,
-0.271728515625,
0.3037109375,
0.031402587890625,
0.91162109375,
0.705078125,
-0.221923828125,
0.51025390625,
-0.67626953125,
-0.5185546875,
0.03363037109375,
-0.2423095703125,
-0.7675... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.
He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).
Implement this feature to help Polycarp test his editor.
Input
The first line contains two integers, w and h (1 β€ w, h β€ 100) β the width and height of an image in pixels. The picture is given in h lines, each line contains w characters β each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.
Output
Print 2w lines, each containing 2h characters β the result of consecutive implementing of the three transformations, described above.
Examples
Input
3 2
.*.
.*.
Output
....
....
****
****
....
....
Input
9 20
**.......
****.....
******...
*******..
..******.
....****.
......***
*.....***
*********
*********
*********
*********
....**...
...****..
..******.
.********
****..***
***...***
**.....**
*.......*
Output
********......**********........********
********......**********........********
********........********......********..
********........********......********..
..********......********....********....
..********......********....********....
..********......********..********......
..********......********..********......
....********....****************........
....********....****************........
....********....****************........
....********....****************........
......******************..**********....
......******************..**********....
........****************....**********..
........****************....**********..
............************......**********
............************......**********
Tags: *special, implementation
Correct Solution:
```
class Image(object):
def __init__ (self, width, height, stringImage):
self._width = width
self._height = height
self._stringImage = stringImage
self._pixelMatrix = [[]]
# filling pixel matrix
line = 0
for i in self._stringImage:
if (i == '\n'):
self._pixelMatrix.append([])
line+=1
else:
self._pixelMatrix[line].append(i)
def __str__ (self):
resultedString = ''
for line in self._pixelMatrix:
for j in line:
resultedString += j
resultedString += '\n'
return resultedString[:-1]
def rotate90right(self):
# new matrix
newPixelMatrix = []
for i in range(self._width):
newPixelMatrix.append([])
for j in range(self._height):
newPixelMatrix[i].append('.')
# rotating elements
for i in range (self._height):
for j in range(self._width):
newPixelMatrix[j][self._height-1-i] = self._pixelMatrix[i][j]
self._pixelMatrix = newPixelMatrix
temp = self._height
self._height = self._width
self._width = temp
def mirrorGorizont(self):
# new matrix
newPixelMatrix = []
for i in range(self._height):
newPixelMatrix.append([])
for j in range(self._width):
newPixelMatrix[i].append('.')
# mirroring elements
for i in range (self._height):
for j in range(self._width):
newPixelMatrix[i][self._width-1-j] = self._pixelMatrix[i][j]
self._pixelMatrix = newPixelMatrix
def doubleTheSize(self):
# creating new matrix, double the size!
newPixelMatrix = []
for i in range(self._height*2):
newPixelMatrix.append([])
for j in range(self._width*2):
newPixelMatrix[i].append('.')
# transport data
for i in range (self._height):
for j in range(self._width):
newPixelMatrix[i*2][j*2] = self._pixelMatrix[i][j]
newPixelMatrix[i*2][j*2+1] = self._pixelMatrix[i][j]
newPixelMatrix[i*2+1][j*2] = self._pixelMatrix[i][j]
newPixelMatrix[i*2+1][j*2+1] = self._pixelMatrix[i][j]
self._pixelMatrix = newPixelMatrix
self._height *= 2
self._width *= 2
inputString = input()
listOfInput = inputString.split()
width = -1
height = -1
for i in listOfInput:
if i.isdigit() and width == -1:
width = int(i)
elif i.isdigit():
height = int(i)
image = input()
for i in range(height-1):
image += '\n'
image += input()
a = Image(width, height, image)
a.doubleTheSize()
a.rotate90right()
a.mirrorGorizont()
print(a)
```
| 48,321 | [
0.4072265625,
-0.15966796875,
0.031768798828125,
-0.06201171875,
-0.316162109375,
-0.35498046875,
-0.271728515625,
0.3037109375,
0.031402587890625,
0.91162109375,
0.705078125,
-0.221923828125,
0.51025390625,
-0.67626953125,
-0.5185546875,
0.03363037109375,
-0.2423095703125,
-0.7675... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.
He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).
Implement this feature to help Polycarp test his editor.
Input
The first line contains two integers, w and h (1 β€ w, h β€ 100) β the width and height of an image in pixels. The picture is given in h lines, each line contains w characters β each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.
Output
Print 2w lines, each containing 2h characters β the result of consecutive implementing of the three transformations, described above.
Examples
Input
3 2
.*.
.*.
Output
....
....
****
****
....
....
Input
9 20
**.......
****.....
******...
*******..
..******.
....****.
......***
*.....***
*********
*********
*********
*********
....**...
...****..
..******.
.********
****..***
***...***
**.....**
*.......*
Output
********......**********........********
********......**********........********
********........********......********..
********........********......********..
..********......********....********....
..********......********....********....
..********......********..********......
..********......********..********......
....********....****************........
....********....****************........
....********....****************........
....********....****************........
......******************..**********....
......******************..**********....
........****************....**********..
........****************....**********..
............************......**********
............************......**********
Tags: *special, implementation
Correct Solution:
```
w, h = map( int, input( ).split( ) )
stgs = [ ]
for i in range( h ):
stgs.append( input( ) )
m = [0] * h
for i in range(h):
m[i] = [0] * w
for i in range( h ):
for j in range( w ):
m[ i ][ j ] = stgs[ i ][ j ]
for i in range( h ):
m[ i ].reverse( )
sk = 1
st = ""
for i in range( w - 1, -1, -1 ):
for j in range( h ):
st += m[ j ][ i ] + m[ j ][ i ]
print( st, st, sep = '\n' )
st = ''
```
| 48,322 | [
0.4072265625,
-0.15966796875,
0.031768798828125,
-0.06201171875,
-0.316162109375,
-0.35498046875,
-0.271728515625,
0.3037109375,
0.031402587890625,
0.91162109375,
0.705078125,
-0.221923828125,
0.51025390625,
-0.67626953125,
-0.5185546875,
0.03363037109375,
-0.2423095703125,
-0.7675... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.
He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).
Implement this feature to help Polycarp test his editor.
Input
The first line contains two integers, w and h (1 β€ w, h β€ 100) β the width and height of an image in pixels. The picture is given in h lines, each line contains w characters β each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.
Output
Print 2w lines, each containing 2h characters β the result of consecutive implementing of the three transformations, described above.
Examples
Input
3 2
.*.
.*.
Output
....
....
****
****
....
....
Input
9 20
**.......
****.....
******...
*******..
..******.
....****.
......***
*.....***
*********
*********
*********
*********
....**...
...****..
..******.
.********
****..***
***...***
**.....**
*.......*
Output
********......**********........********
********......**********........********
********........********......********..
********........********......********..
..********......********....********....
..********......********....********....
..********......********..********......
..********......********..********......
....********....****************........
....********....****************........
....********....****************........
....********....****************........
......******************..**********....
......******************..**********....
........****************....**********..
........****************....**********..
............************......**********
............************......**********
Tags: *special, implementation
Correct Solution:
```
W, H = map( int, input().split() )
mat = [ input() for i in range( H ) ]
for i in range( 2 * W ):
print( ''.join( mat[ j // 2 ][ i // 2 ] for j in range( 2 * H ) ) )
```
| 48,323 | [
0.4072265625,
-0.15966796875,
0.031768798828125,
-0.06201171875,
-0.316162109375,
-0.35498046875,
-0.271728515625,
0.3037109375,
0.031402587890625,
0.91162109375,
0.705078125,
-0.221923828125,
0.51025390625,
-0.67626953125,
-0.5185546875,
0.03363037109375,
-0.2423095703125,
-0.7675... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.
He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).
Implement this feature to help Polycarp test his editor.
Input
The first line contains two integers, w and h (1 β€ w, h β€ 100) β the width and height of an image in pixels. The picture is given in h lines, each line contains w characters β each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.
Output
Print 2w lines, each containing 2h characters β the result of consecutive implementing of the three transformations, described above.
Examples
Input
3 2
.*.
.*.
Output
....
....
****
****
....
....
Input
9 20
**.......
****.....
******...
*******..
..******.
....****.
......***
*.....***
*********
*********
*********
*********
....**...
...****..
..******.
.********
****..***
***...***
**.....**
*.......*
Output
********......**********........********
********......**********........********
********........********......********..
********........********......********..
..********......********....********....
..********......********....********....
..********......********..********......
..********......********..********......
....********....****************........
....********....****************........
....********....****************........
....********....****************........
......******************..**********....
......******************..**********....
........****************....**********..
........****************....**********..
............************......**********
............************......**********
Tags: *special, implementation
Correct Solution:
```
w, h = map(int, input().split())
a = []
for i in range(h):
a.append(input())
b = [[None]*(2*h) for _ in range(2*w)]
for i in range(w):
for j in range(h):
b[2*i ][2*j ] = a[j][i]
b[2*i ][2*j+1] = a[j][i]
b[2*i+1][2*j ] = a[j][i]
b[2*i+1][2*j+1] = a[j][i]
print('\n'.join([''.join(i) for i in b]))
```
| 48,324 | [
0.4072265625,
-0.15966796875,
0.031768798828125,
-0.06201171875,
-0.316162109375,
-0.35498046875,
-0.271728515625,
0.3037109375,
0.031402587890625,
0.91162109375,
0.705078125,
-0.221923828125,
0.51025390625,
-0.67626953125,
-0.5185546875,
0.03363037109375,
-0.2423095703125,
-0.7675... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.
He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).
Implement this feature to help Polycarp test his editor.
Input
The first line contains two integers, w and h (1 β€ w, h β€ 100) β the width and height of an image in pixels. The picture is given in h lines, each line contains w characters β each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.
Output
Print 2w lines, each containing 2h characters β the result of consecutive implementing of the three transformations, described above.
Examples
Input
3 2
.*.
.*.
Output
....
....
****
****
....
....
Input
9 20
**.......
****.....
******...
*******..
..******.
....****.
......***
*.....***
*********
*********
*********
*********
....**...
...****..
..******.
.********
****..***
***...***
**.....**
*.......*
Output
********......**********........********
********......**********........********
********........********......********..
********........********......********..
..********......********....********....
..********......********....********....
..********......********..********......
..********......********..********......
....********....****************........
....********....****************........
....********....****************........
....********....****************........
......******************..**********....
......******************..**********....
........****************....**********..
........****************....**********..
............************......**********
............************......**********
Tags: *special, implementation
Correct Solution:
```
I=input
R=range
w,h=map(int,I().split())
t=[I()for _ in R(h)]
for r in[[t[i][j]*2for i in R(h)]for j in R(w)]:s=''.join(r);print(s+'\n'+s)
```
| 48,325 | [
0.4072265625,
-0.15966796875,
0.031768798828125,
-0.06201171875,
-0.316162109375,
-0.35498046875,
-0.271728515625,
0.3037109375,
0.031402587890625,
0.91162109375,
0.705078125,
-0.221923828125,
0.51025390625,
-0.67626953125,
-0.5185546875,
0.03363037109375,
-0.2423095703125,
-0.7675... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Tags: data structures, implementation
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 16 10:58:05 2021
@author: ludoj
klanten=[]
res=[]
tel=1
for a in range(q):
if len(b[a])==2:
klanten.append((b[a][1],tel))
tel+=1
if b[a][0]==2:
res.append(klanten.pop(0)[1])
if b[a][0]==3:
maxi=max([x[0] for x in klanten])
tel2=0
while(maxi!=klanten[tel2][0]):
tel2+=1
res.append(klanten.pop(tel2)[1])
print(*res)
"""
import heapq
q=int(input())
b=[]
for a in range(q):
b.append([int(x) for x in input().split()])
klanten=[]
heapq.heapify(klanten)
weg=[]
res=[]
tel=1
i=0
for a in range(q):
if len(b[a])==2:
heapq.heappush(klanten,(-b[a][1],tel))
weg.append(False)
tel+=1
if b[a][0]==2:
while(weg[i]):
i+=1
weg[i]=True
res.append(str(i+1))
if b[a][0]==3:
stop=True
while(stop):
item=heapq.heappop(klanten)
if weg[item[1]-1]==False:
res.append(str(item[1]))
weg[item[1]-1]=True
stop=False
print(*res)
```
| 49,042 | [
0.269775390625,
0.11468505859375,
-0.05743408203125,
0.1756591796875,
-0.251953125,
-0.367919921875,
-0.4912109375,
0.219482421875,
0.185302734375,
0.51611328125,
0.86181640625,
-0.133544921875,
0.53564453125,
-0.402099609375,
-0.89404296875,
0.1795654296875,
-0.75634765625,
-0.603... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Tags: data structures, implementation
Correct Solution:
```
import re
import sys
exit=sys.exit
from bisect import bisect_left as bsl,bisect_right as bsr
from collections import Counter,defaultdict as ddict,deque
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum=enumerate
ri=lambda:int(rln())
ris=lambda:list(map(int,rfs()))
rln=sys.stdin.readline
rl=lambda:rln().rstrip('\n')
rfs=lambda:rln().split()
d4=[(0,-1),(1,0),(0,1),(-1,0)]
d8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
########################################################################
q=ri()
a,b=[],[]
ans=[]
i=0
served=set()
for _ in range(q):
op,m,*_=ris()+[0]
if op==1:
i+=1
heappush(a,( i,i))
heappush(b,(-m,i))
else:
hp={2:a,3:b}[op]
while 1:
_,j=heappop(hp)
if j not in served:
break
served.discard(j)
ans.append(j)
served.add(j)
print(*ans)
```
| 49,043 | [
0.269775390625,
0.11468505859375,
-0.05743408203125,
0.1756591796875,
-0.251953125,
-0.367919921875,
-0.4912109375,
0.219482421875,
0.185302734375,
0.51611328125,
0.86181640625,
-0.133544921875,
0.53564453125,
-0.402099609375,
-0.89404296875,
0.1795654296875,
-0.75634765625,
-0.603... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Tags: data structures, implementation
Correct Solution:
```
from sys import stdin, stdout
def insert(ID):
heap.append(ID)
i = len(heap)-1
while (i - 1) // 2 >= 0 and (score[heap[(i - 1) // 2]] < score[heap[i]] or (
score[heap[(i - 1) // 2]] == score[heap[i]] and heap[i] < heap[(i - 1) // 2])):
heap[(i - 1) // 2] += heap[i]
heap[i] = heap[(i - 1) // 2] - heap[i]
heap[(i - 1) // 2] -= heap[i]
i = (i-1)//2
def remove():
if len(heap) == 1:
return heap.pop()
else:
heap[0] += heap[-1]
heap[-1] = heap[0] - heap[-1]
heap[0] -= heap[-1]
res = heap.pop()
n, i = len(heap), 0
while (2 * i) + 1 < n:
maxm = (2 * i) + 1
if (2 * i) + 2 < n and score[heap[(2 * i) + 2]] > score[heap[maxm]]:
maxm = (2 * i) + 2
elif (2 * i) + 2 < n and (score[heap[(2 * i) + 2]] == score[heap[maxm]] and heap[maxm] > heap[(2 * i) + 2]):
maxm = (2 * i) + 2
if (score[heap[i]] > score[heap[maxm]]) or (score[heap[i]] == score[heap[maxm]] and heap[maxm] > heap[i]):
break
heap[maxm] += heap[i]
heap[i] = heap[maxm] - heap[i]
heap[maxm] -= heap[i]
i = maxm
return res
N = int(stdin.readline())
score = dict()
heap = []
output = []
visited = dict()
n = 1
i = 1
for __ in range(N):
x = [int(num) for num in stdin.readline().strip().split()]
if x[0] == 1:
score[n] = x[1]
insert(n)
n += 1
elif x[0] == 2:
while visited.get(i, False):
i += 1
visited[i] = True
output.append(i)
i += 1
else:
res = remove()
while visited.get(res, False):
res = remove()
output.append(res)
visited[res] = True
for out in output[:len(output)-1]:
stdout.write(f'{out} ')
stdout.write(f'{output[-1]}')
```
| 49,044 | [
0.269775390625,
0.11468505859375,
-0.05743408203125,
0.1756591796875,
-0.251953125,
-0.367919921875,
-0.4912109375,
0.219482421875,
0.185302734375,
0.51611328125,
0.86181640625,
-0.133544921875,
0.53564453125,
-0.402099609375,
-0.89404296875,
0.1795654296875,
-0.75634765625,
-0.603... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Tags: data structures, implementation
Correct Solution:
```
# from __future__ import print_function,division
# range = xrange
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10**9)
from sys import stdin, stdout
from collections import defaultdict, Counter,deque
M = 10**9+7
import heapq
def main():
n = int(input())
vis = []
q = deque([])
h = []
ind = 0
ans = []
for i in range(n):
l = [int(s) for s in input().split()]
if l[0]==1:
vis.append(0)
q.append([l[1],ind])
heapq.heappush(h,[-l[1],ind])
ind+=1
elif l[0]==2:
w = q.popleft()
while vis[w[1]]==1:
w = q.popleft()
ans.append(w[1]+1)
vis[w[1]] = 1
else:
w = heapq.heappop(h)
while vis[w[1]]==1:
w = heapq.heappop(h)
ans.append(w[1]+1)
vis[w[1]] = 1
print(*ans)
if __name__== '__main__':
main()
```
| 49,045 | [
0.269775390625,
0.11468505859375,
-0.05743408203125,
0.1756591796875,
-0.251953125,
-0.367919921875,
-0.4912109375,
0.219482421875,
0.185302734375,
0.51611328125,
0.86181640625,
-0.133544921875,
0.53564453125,
-0.402099609375,
-0.89404296875,
0.1795654296875,
-0.75634765625,
-0.603... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Tags: data structures, implementation
Correct Solution:
```
from sys import stdin
import heapq
q = int(stdin.readline())
endlis = []
mono = 0
hq = []
ans = []
for loop in range(q):
query = input()
if query[0] == "1":
tmp,m = map(int,query.split())
endlis.append(0)
heapq.heappush(hq,(-1*m,len(endlis)-1))
elif query[0] == "2":
while endlis[mono] == 1:
mono += 1
ans.append(mono+1)
endlis[mono] = 1
else:
while endlis[ hq[0][1] ] == 1:
heapq.heappop(hq)
tmp,ind = heapq.heappop(hq)
ans.append(ind+1)
endlis[ind] = 1
print (*ans)
```
| 49,046 | [
0.269775390625,
0.11468505859375,
-0.05743408203125,
0.1756591796875,
-0.251953125,
-0.367919921875,
-0.4912109375,
0.219482421875,
0.185302734375,
0.51611328125,
0.86181640625,
-0.133544921875,
0.53564453125,
-0.402099609375,
-0.89404296875,
0.1795654296875,
-0.75634765625,
-0.603... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Tags: data structures, implementation
Correct Solution:
```
from sys import stdin,stdout
from heapq import heappop,heappush
def main():
ans,visited,hp=[],[],[]
start=0
for _ in range(int(stdin.readline())):
q=stdin.readline()
if q[0]=="1":
_,v=map(int,q.split( ))
visited.append(0)
heappush(hp,(-1*v,len(visited)-1))
elif q[0]=="2":
while visited[start]==1:
start+=1
ans.append(start+1)
visited[start]=1
else:
while visited[hp[0][1]]==1:
heappop(hp)
_,ind=heappop(hp)
ans.append(ind+1)
visited[ind]=1
for v in ans:
stdout.write("%d "%(v))
stdout.write("\n")
main()
```
| 49,047 | [
0.269775390625,
0.11468505859375,
-0.05743408203125,
0.1756591796875,
-0.251953125,
-0.367919921875,
-0.4912109375,
0.219482421875,
0.185302734375,
0.51611328125,
0.86181640625,
-0.133544921875,
0.53564453125,
-0.402099609375,
-0.89404296875,
0.1795654296875,
-0.75634765625,
-0.603... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Tags: data structures, implementation
Correct Solution:
```
import heapq
def solution(n: int, arr: [[int]]) -> [int]:
queue = []
heap = []
result = []
lastIndex = 0
for i in arr:
if i[0] == 1:
lastIndex += 1
element = [-i[1], lastIndex, False]
queue.append(element)
heapq.heappush(heap, element)
if i[0] == 2:
customer = queue.pop(0)
while customer[2] == True:
customer = queue.pop(0)
customer[2] = True
result.append(customer[1])
if i[0] == 3:
customer = heapq.heappop(heap)
while customer[2] == True:
customer = heapq.heappop(heap)
customer[2] = True
result.append(customer[1])
return result
def main():
n = int(input())
arr = [[int(j) for j in input().split(" ")] for i in range(n)]
print(" ".join([str(i) for i in solution(n, arr)]))
if __name__ == '__main__':
main()
```
| 49,048 | [
0.269775390625,
0.11468505859375,
-0.05743408203125,
0.1756591796875,
-0.251953125,
-0.367919921875,
-0.4912109375,
0.219482421875,
0.185302734375,
0.51611328125,
0.86181640625,
-0.133544921875,
0.53564453125,
-0.402099609375,
-0.89404296875,
0.1795654296875,
-0.75634765625,
-0.603... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Tags: data structures, implementation
Correct Solution:
```
import os
import math
import statistics
import heapq
true = True;
false = False;
# from collections import defaultdict, deque
from functools import reduce
is_dev = 'vscode' in os.environ
if is_dev:
inF = open('in.txt', 'r')
outF = open('out.txt', 'w')
def ins():
return list(map(int, input_().split(' ')))
def inss():
return list(input_().split(' '))
def input_():
if is_dev:
return inF.readline()[:-1]
else:
return input()
def ranin():
return range(int(input_()))
def print_(data):
if is_dev:
outF.write(str(data)+'\n')
else:
print(data)
epsilon = 1e-7
customers = []
heapq.heapify(customers)
i = 1
j = 1
served = [False]*(5*(10**5)+2)
result = []
for _ in range(int(input_())):
a = ins()
if a[0] == 1:
heapq.heappush(customers, (-a[1], i))
i+=1
elif a[0] == 2:
while served[j]:
j += 1
served[j] = True
result.append(j)
j += 1
elif a[0] == 3:
customer = heapq.heappop(customers)
while served[customer[1]]:
customer = heapq.heappop(customers)
served[customer[1]] = True
result.append(customer[1])
print_(' '.join(map(str, result)))
if is_dev:
outF.close()
def compare_file():
print(open('out.txt', 'r').read() == open('outactual.txt', 'r').read())
compare_file()
```
| 49,049 | [
0.269775390625,
0.11468505859375,
-0.05743408203125,
0.1756591796875,
-0.251953125,
-0.367919921875,
-0.4912109375,
0.219482421875,
0.185302734375,
0.51611328125,
0.86181640625,
-0.133544921875,
0.53564453125,
-0.402099609375,
-0.89404296875,
0.1795654296875,
-0.75634765625,
-0.603... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Submitted Solution:
```
import heapq
mono = []
poly = []
d={}
count = 1
ans=[]
q = int(input())
for i in range(q):
query = list(input().split())
if len(query)>1:
heapq.heappush(mono,[count,int(query[1])])
heapq.heappush(poly,[-int(query[1]),count])
count+=1
else:
if query[0]=="2":
while 1:
p = heapq.heappop(mono)
try:
del d[p[0]]
except:
ans.append(p[0])
# print(p[0],end=" ")
d[p[0]]=1
break
elif query[0]=="3":
while 1:
p = heapq.heappop(poly)
try:
del d[p[1]]
except:
ans.append(p[1])
# print(p[1],end=" ")
d[p[1]]=1
break
print(*ans)
```
Yes
| 49,050 | [
0.307861328125,
0.1134033203125,
-0.1019287109375,
0.1923828125,
-0.2095947265625,
-0.2294921875,
-0.53515625,
0.24755859375,
0.18505859375,
0.477783203125,
0.767578125,
-0.1212158203125,
0.52490234375,
-0.41162109375,
-0.89501953125,
0.20556640625,
-0.69775390625,
-0.70166015625,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Submitted Solution:
```
# Author Name: Ajay Meena
# Codeforce : https://codeforces.com/profile/majay1638
# -------- IMPORTANT ---------#
# SUN BHOS**KE AGAR MERA TEMPLATE COPY KAR RHA HAI NA TOH KUCH CHANGES BHI KAR DENA ESS ME, VARNA MUJEHY WARNING AAYEGI BAAD ME, PLEASE YAAR KAR DENA, OK :).
import sys
import heapq
from heapq import heappush, heappop
import math
from sys import stdin, stdout
# //Most Frequently Used Number Theory Concepts
# VAISE MEIN JAYDA USE KARTA NHI HU ENHE BUT COOL BANNE KE LIYE LIKH LEYA TEMPLATE ME VARNA ME YE TOH DUSRI FILE MAI SE BHI COPY PASTE KAR SAKTA THA :).
def sieve(N):
primeNumbers = [True]*(N+1)
primeNumbers[0] = False
primeNumbers[1] = False
i = 2
while i*i <= N:
j = i
if primeNumbers[j]:
while j*i <= N:
primeNumbers[j*i] = False
j += 1
i += 1
return primeNumbers
def getPrime(N):
primes = sieve(N)
result = []
for i in range(len(primes)):
if primes[i]:
result.append(i)
return result
def factor(N):
factors = []
i = 1
while i*i <= N:
if N % i == 0:
factors.append(i)
if i != N//i:
factors.append(N//i)
i += 1
return sorted(factors)
def gcd(a, b):
if a < b:
return gcd(b, a)
if b == 0:
return a
return gcd(b, a % b)
def extendedGcd(a, b):
if a < b:
return extendedGcd(b, a)
if b == 0:
return [a, 1, 0]
res = extendedGcd(b, a % b)
x = res[2]
y = res[1]-(math.floor(a/b)*res[2])
res[1] = x
res[2] = y
return res
def iterativeModularFunc(a, b, c):
res = 1
while b > 0:
if b & 1:
res = (res*a) % c
a = (a*a) % c
b = b//2
return res
# TAKE INPUT
# HAAN YE BHUT KAAM AATA HAI INPUT LENE ME
def get_ints_in_variables():
return map(int, sys.stdin.readline().strip().split())
def get_int(): return int(input())
def get_ints_in_list(): return list(
map(int, sys.stdin.readline().strip().split()))
def get_list_of_list(n): return [list(
map(int, sys.stdin.readline().strip().split())) for _ in range(n)]
def get_string(): return sys.stdin.readline().strip()
def Solution():
heap = []
hm = []
idx = 0
# queue = []
# i = 1
res = []
for _ in range(get_int()):
q = input()
if q[0] == "1":
ip = list(map(int, q.split()))
v = ip[1]
hm.append(0)
heappush(heap, (-1*v, len(hm)-1))
elif q[0] == "2":
while hm[idx] == 1:
idx += 1
hm[idx] = 1
res.append(idx+1)
else:
while hm[heap[0][1]] == 1:
heappop(heap)
itm = heappop(heap)
hm[itm[1]] = 1
res.append(itm[1]+1)
print(*res)
def main():
# //Write Your Code Here
Solution()
# calling main Function
if __name__ == "__main__":
main()
```
Yes
| 49,051 | [
0.307861328125,
0.1134033203125,
-0.1019287109375,
0.1923828125,
-0.2095947265625,
-0.2294921875,
-0.53515625,
0.24755859375,
0.18505859375,
0.477783203125,
0.767578125,
-0.1212158203125,
0.52490234375,
-0.41162109375,
-0.89501953125,
0.20556640625,
-0.69775390625,
-0.70166015625,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 16 10:58:05 2021
@author: ludoj
klanten=[]
res=[]
tel=1
for a in range(q):
if len(b[a])==2:
klanten.append((b[a][1],tel))
tel+=1
if b[a][0]==2:
res.append(klanten.pop(0)[1])
if b[a][0]==3:
maxi=max([x[0] for x in klanten])
tel2=0
while(maxi!=klanten[tel2][0]):
tel2+=1
res.append(klanten.pop(tel2)[1])
print(*res)
"""
import heapq
q=int(input())
b=[]
for a in range(q):
b.append([int(x) for x in input().split()])
klanten=[]
heapq.heapify(klanten)
weg=[]
res=[]
tel=1
i=0
for a in range(q):
if len(b[a])==2:
heapq.heappush(klanten,(-b[a][1],tel))
weg.append(False)
tel+=1
if b[a][0]==2:
while(weg[i]):
i+=1
weg[i]=True
res.append(str(i+1))
if b[a][0]==3:
stop=True
while(stop):
item=heapq.heappop(klanten)
if weg[item[1]-1]==False:
res.append(str(item[1]))
weg[item[1]-1]=True
stop=False
print(" ".join(res))
```
Yes
| 49,052 | [
0.307861328125,
0.1134033203125,
-0.1019287109375,
0.1923828125,
-0.2095947265625,
-0.2294921875,
-0.53515625,
0.24755859375,
0.18505859375,
0.477783203125,
0.767578125,
-0.1212158203125,
0.52490234375,
-0.41162109375,
-0.89501953125,
0.20556640625,
-0.69775390625,
-0.70166015625,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Submitted Solution:
```
#!python3
from queue import PriorityQueue, Queue
import sys
class Customer(object):
def __init__(self, i):
self.i = i
self.seen = False
def __lt__(self, other):
return self.i < other.i
def parse_input():
test_count = int(sys.stdin.readline())
poly_customers = PriorityQueue()
mono_customers = Queue()
i = 0
for _ in range(test_count):
line = sys.stdin.readline().strip()
if line.startswith('1'):
a, b = line.split(' ', maxsplit=1)
a, b = int(a), int(b)
i += 1
c = Customer(i)
poly_customers.put((-b, c))
mono_customers.put(c)
else:
c = int(line)
if c == 2:
yield get_mono(mono_customers)
# sys.stdout.write(f'{o}\n')
elif c == 3:
yield get_poly(poly_customers)
# sys.stdout.write(f'{o}\n')
else:
raise Exception
def get_mono(mono_customers):
c = mono_customers.get()
while c.seen:
c = mono_customers.get()
c.seen = True
return c.i
def get_poly(poly_customers):
_, c = poly_customers.get()
while c.seen:
_, c = poly_customers.get()
c.seen = True
return c.i
def main():
for o in parse_input():
sys.stdout.write(f'{o}\n')
main()
```
Yes
| 49,053 | [
0.307861328125,
0.1134033203125,
-0.1019287109375,
0.1923828125,
-0.2095947265625,
-0.2294921875,
-0.53515625,
0.24755859375,
0.18505859375,
0.477783203125,
0.767578125,
-0.1212158203125,
0.52490234375,
-0.41162109375,
-0.89501953125,
0.20556640625,
-0.69775390625,
-0.70166015625,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Submitted Solution:
```
lines = []
num = int(input("input:\n"))
for i in range(num):
line = input("")
lines.append(line)
output = ""
customs = {}
customs_reverse = {}
count = 1
for line in lines:
if line[0] == "1":
value = int(line[2:])
customs[count] = value
if value in customs_reverse:
customs_reverse[value].append(count)
else:
customs_reverse[value] = [count]
count += 1
elif line[0] == "2":
key1 = min(customs.keys())
value1 = customs[key1]
output += f"{key1}"+" "
customs.pop(key1)
customs_reverse[value1].remove(key1)
elif line[0] == "3":
value2 = max(customs_reverse.keys())
key2 = min(customs_reverse[value2])
output += f"{key2}"+" "
customs.pop(key2)
customs_reverse[value2].remove(key2)
if not customs_reverse[value2]:
customs_reverse.pop(value2)
print(output[:-1])
```
No
| 49,054 | [
0.307861328125,
0.1134033203125,
-0.1019287109375,
0.1923828125,
-0.2095947265625,
-0.2294921875,
-0.53515625,
0.24755859375,
0.18505859375,
0.477783203125,
0.767578125,
-0.1212158203125,
0.52490234375,
-0.41162109375,
-0.89501953125,
0.20556640625,
-0.69775390625,
-0.70166015625,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Submitted Solution:
```
q=int(input())
l=[]
turn = 0
served={}
pointer=1
weight={}
p=0
j=0
ans=[]
for i in range(q):
query = list(map(int,input().split()))
if query[0]==1:
turn=turn+1
served[turn]=0
weight[turn]=query[1]
l.append((1,query[1],turn))
elif query[0] == 2:
#if pointer!=1 and served[pointer]==0:
# served[pointer]=1
# print(pointer)
# while served[pointer]!=0:
# pointer+=1
if pointer in served:
if served[pointer]==0:
served[pointer]=1
#print(pointer)
ans.append(pointer)
while pointer in served and served[pointer]!=0:
pointer+=1
#print(pointer)
elif served[pointer]==1:
while pointer in served and served[pointer]!=0:
pointer+=1
#print(pointer)
ans.append(pointer)
elif query[0]==3:
#find the maximum weight key which is not in served
v = {k: v for k, v in sorted(weight.items(), key=lambda item: item[1],reverse=True)}
vI=v.items()
lVI=list(vI)
for u in range(j,len(lVI)):
if served[lVI[u][0]]==0:
served[lVI[u][0]]=1
#print(k)
ans.append(lVI[u][0])
j+=1
break
else:
j+=1
#continue
print(*ans)
```
No
| 49,055 | [
0.307861328125,
0.1134033203125,
-0.1019287109375,
0.1923828125,
-0.2095947265625,
-0.2294921875,
-0.53515625,
0.24755859375,
0.18505859375,
0.477783203125,
0.767578125,
-0.1212158203125,
0.52490234375,
-0.41162109375,
-0.89501953125,
0.20556640625,
-0.69775390625,
-0.70166015625,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Submitted Solution:
```
def argsort(seq):
return sorted(range(len(seq)), key=seq.__getitem__,reverse=True)
a = []
s=0
numbers = 1
served = []
crowd = int(input())
for _ in range(crowd):
p = [int(x) for x in input().split()]
if len(p)==2:
s+=1
a.append(p[1])
else:
q = argsort(a)
if len(q)>0:
for i in q:
served.append(i+numbers)
numbers+=len(q)
a=[]
t = max(min(s,crowd-s),s//2)
print(*served[:t])
```
No
| 49,056 | [
0.307861328125,
0.1134033203125,
-0.1019287109375,
0.1923828125,
-0.2095947265625,
-0.2294921875,
-0.53515625,
0.24755859375,
0.18505859375,
0.477783203125,
0.767578125,
-0.1212158203125,
0.52490234375,
-0.41162109375,
-0.89501953125,
0.20556640625,
-0.69775390625,
-0.70166015625,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.
At the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.
On the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).
Obviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.
When the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:
* 1 m β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).
For each query of types 2 and 3, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from 1).
Input
The first line contains one integer q (2 β€ q β€ 5 β
10^5) β the number of queries.
Then q lines follow, each describing a query in one of the following formats:
* 1 m (1 β€ m β€ 5 β
10^5) β a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as m;
* 2 β Monocarp serves a customer which came to the pizzeria first;
* 3 β Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are multiple such customers, the one that came to the pizzeria first is chosen).
Queries of type 2 and 3 are asked only when there exists at least one customer that hasn't been served yet. There is at least one query of type 2 or 3 in the input.
Output
For each query of type 2 or 3, print one integer β the number of the customer that has been served in that event. The customers are numbered in the order in which they come to the pizzeria, starting from 1.
Examples
Input
8
1 8
1 10
1 6
3
2
1 9
2
3
Output
2 1 3 4
Input
6
1 8
1 10
1 8
3
3
3
Output
2 1 3
Input
8
1 103913
3
1 103913
1 103913
3
1 103913
1 103913
2
Output
1 2 3
Submitted Solution:
```
Q=int(input())
A1=[]
A2=[]
#A3=[]
maxm = -1
maxm_index = 0
maxm_index_val=0
m=1
numofdeleted=0
for q in range(Q):
z=input()
a1,a2=-1,-1
if len(z) > 1:
a1, a2 = z.split()
a1, a2 = int(a1), int(a2)
A1.append(m)
A2.append(a2)
if A2[len(A2) - 1] > maxm:
maxm = A2[len(A2) - 1]
maxm_index = A1[len(A2) - 1]-1
maxm_index_val=len(A2) - 1
#A3.append(False)
#print(A1)
m+=1
#print(A1,maxm,maxm_index)
else:
z = int(z)
if z == 2:
for i in range(len(A1)):
print(A1[0])
A1.pop(0)
A2.pop(0)
break
maxm=-1
maxm_index=-1
maxm = -1
maxm_index = -1
maxm_index_val = -1
for j in range(len(A1)):
if A2[j] > maxm:
maxm = A2[j]
maxm_index = A1[j] - 1
maxm_index_val = j
if z == 3:
if A2[len(A2)-1] > maxm:
maxm = A2[len(A2)-1]
maxm_index = len(A2)-1
print(maxm_index+1, end=" ")
#print(A1,len(A1),end=" ")
A1.pop(maxm_index_val)
A2.pop(maxm_index_val)
maxm = -1
maxm_index = -1
maxm_index_val=-1
for j in range(len(A1)):
if A2[j] > maxm:
maxm = A2[j]
maxm_index = A1[j]-1
maxm_index_val=j
elif A2[j] == maxm:
maxm = A2[j]
maxm_index = A1[j]-1
maxm_index_val=j
break
#print(maxm,maxm_index)
```
No
| 49,057 | [
0.307861328125,
0.1134033203125,
-0.1019287109375,
0.1923828125,
-0.2095947265625,
-0.2294921875,
-0.53515625,
0.24755859375,
0.18505859375,
0.477783203125,
0.767578125,
-0.1212158203125,
0.52490234375,
-0.41162109375,
-0.89501953125,
0.20556640625,
-0.69775390625,
-0.70166015625,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Tags: *special, binary search, constructive algorithms, data structures, sortings
Correct Solution:
```
n = int(input())
chat = {}
for i in range(n):
chat[input()] = i
c = {}
for i in chat.keys():
c[chat[i]] = i
m = []
for i in sorted(list(c.keys()), reverse = True):
m.append(c[i])
print(*m, sep = '\n')
```
| 49,268 | [
0.28857421875,
-0.0718994140625,
0.427490234375,
0.427001953125,
0.1768798828125,
-0.60693359375,
-0.418701171875,
0.21044921875,
0.396240234375,
0.322509765625,
0.48095703125,
-0.1007080078125,
0.277099609375,
-0.6943359375,
-0.689453125,
-0.0311431884765625,
-0.7373046875,
-0.631... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Tags: *special, binary search, constructive algorithms, data structures, sortings
Correct Solution:
```
n =int(input())
arr =[]
for i in range(n):
arr.append(input())
arr =arr[::-1]
string =set()
for a in arr:
if (a not in string):
string.add(a)
print (a)
```
| 49,269 | [
0.235595703125,
-0.051513671875,
0.45654296875,
0.44921875,
0.1524658203125,
-0.63623046875,
-0.405029296875,
0.203369140625,
0.37890625,
0.312255859375,
0.5029296875,
-0.1016845703125,
0.2646484375,
-0.7294921875,
-0.69189453125,
-0.0562744140625,
-0.77734375,
-0.626953125,
-0.5... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Tags: *special, binary search, constructive algorithms, data structures, sortings
Correct Solution:
```
t = int(input())
q = list()
for i in range(t):
n = (input())
q.append(n)
s = set(q)
while len(s) > 0:
for j in q[::-1]:
if j in s:
print(j)
s.remove(j)
else:
break
```
| 49,270 | [
0.25341796875,
-0.047515869140625,
0.4736328125,
0.429443359375,
0.1439208984375,
-0.6064453125,
-0.42529296875,
0.2203369140625,
0.344970703125,
0.3037109375,
0.462646484375,
-0.09521484375,
0.2578125,
-0.734375,
-0.6962890625,
-0.04119873046875,
-0.75244140625,
-0.669921875,
-0... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Tags: *special, binary search, constructive algorithms, data structures, sortings
Correct Solution:
```
n = int(input())
displayed = {}
top = None
for i in range(n):
chat = input()
try:
a = displayed[chat]
previous = a[0]
nextone = a[1]
if previous:
displayed[previous][1] = nextone
if nextone: displayed[nextone][0]=previous
displayed[chat] = [None, top]
if top:
displayed[top][0] = chat
top = chat
except KeyError:
displayed[chat] = [None, top]
if top:
displayed[top][0] = chat
top = chat
#print(displayed)
#print(top)
li = []
while top:
#print(top)
li.append(top)
top = displayed.pop(top)[1]
#print(displayed)
print('\n'.join(li))
```
| 49,271 | [
0.274169921875,
-0.0859375,
0.452392578125,
0.443115234375,
0.1793212890625,
-0.6455078125,
-0.400146484375,
0.189208984375,
0.411865234375,
0.29052734375,
0.463623046875,
-0.08416748046875,
0.276123046875,
-0.6708984375,
-0.72119140625,
-0.0408935546875,
-0.7529296875,
-0.62158203... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Tags: *special, binary search, constructive algorithms, data structures, sortings
Correct Solution:
```
import math,sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda:int(input())
li = lambda:list(map(int,input().split()))
def case():
n=I()
a=[]
for i in range(n):
a.append(input().strip())
s=set([])
i=1
while(i<=n):
if(a[-i] not in s):
print(a[-i])
s.add(a[-i])
i+=1
for _ in range(1):
case()
```
| 49,272 | [
0.274169921875,
-0.03271484375,
0.47607421875,
0.43115234375,
0.145263671875,
-0.63720703125,
-0.43359375,
0.1680908203125,
0.394775390625,
0.356689453125,
0.46142578125,
-0.11065673828125,
0.2880859375,
-0.6767578125,
-0.6943359375,
-0.057098388671875,
-0.7197265625,
-0.625,
-0.... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Tags: *special, binary search, constructive algorithms, data structures, sortings
Correct Solution:
```
n = int(input())
l = []
for _ in range(n):
l.append(input())
answer = []
s = set()
for i in range(n - 1, -1, -1):
if l[i] not in s:
s.add(l[i])
answer.append(l[i])
for _ in answer:
print(_)
```
| 49,273 | [
0.283447265625,
-0.05126953125,
0.449951171875,
0.456298828125,
0.18408203125,
-0.60986328125,
-0.405517578125,
0.20458984375,
0.3720703125,
0.321044921875,
0.477294921875,
-0.08905029296875,
0.27783203125,
-0.6689453125,
-0.671875,
-0.0178680419921875,
-0.74951171875,
-0.645507812... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Tags: *special, binary search, constructive algorithms, data structures, sortings
Correct Solution:
```
n = int(input())
D = {}
l = []
ll = []
for i in range(0,n):
l.append(input())
for i in range(0,n):
if l[n-i-1] in D:
m = 0
else:
D[l[n-i-1]] = 1
ll.append(l[n-1-i])
for i in range(0,len(ll)):
print(ll[i])
```
| 49,274 | [
0.287109375,
-0.07427978515625,
0.480712890625,
0.428955078125,
0.15771484375,
-0.63525390625,
-0.38134765625,
0.18603515625,
0.4033203125,
0.313232421875,
0.48876953125,
-0.0780029296875,
0.268310546875,
-0.689453125,
-0.70263671875,
-0.032257080078125,
-0.75146484375,
-0.64208984... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Tags: *special, binary search, constructive algorithms, data structures, sortings
Correct Solution:
```
n=int(input())
m={}
mm={}
for i in range(n):
a=input()
m[a]=i
for j in m:
mm[m[j]]=j
ans=sorted(mm.keys(),reverse=True)
for i in ans:
print(mm[i])
```
| 49,275 | [
0.282958984375,
-0.0673828125,
0.4462890625,
0.4365234375,
0.173828125,
-0.60888671875,
-0.42431640625,
0.21240234375,
0.35400390625,
0.3056640625,
0.486083984375,
-0.09759521484375,
0.260498046875,
-0.70703125,
-0.69189453125,
-0.040618896484375,
-0.712890625,
-0.63916015625,
-0... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Submitted Solution:
```
n = int(input())
names = {}
for i in range(n):
name = input()
names[name]=i
for name, key in sorted(zip(names.values(), names.keys()), reverse=True):
print(key)
```
Yes
| 49,276 | [
0.3828125,
0.002002716064453125,
0.36962890625,
0.390380859375,
0.05841064453125,
-0.5087890625,
-0.529296875,
0.369384765625,
0.25439453125,
0.283935546875,
0.51318359375,
-0.11883544921875,
0.351806640625,
-0.6728515625,
-0.64111328125,
-0.018890380859375,
-0.7080078125,
-0.59912... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Submitted Solution:
```
def get_chats(names):
chats = {}
for name in reversed(names):
if name not in chats:
print(name)
chats[name] = True
if __name__ == "__main__":
len = int(input())
names = []
for i in range(len):
names.append(input())
get_chats(names)
```
Yes
| 49,277 | [
0.3701171875,
-0.0181884765625,
0.36376953125,
0.40380859375,
0.0548095703125,
-0.5126953125,
-0.52294921875,
0.38134765625,
0.282470703125,
0.293212890625,
0.53955078125,
-0.111572265625,
0.36572265625,
-0.681640625,
-0.6552734375,
-0.037506103515625,
-0.73974609375,
-0.5625,
-0... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Submitted Solution:
```
n = int(input())
rank = n
li = [0] * (n + 1)
for i in range(n, 0, -1):
s = input()
li[i] = s
dp = dict()
for i in range(1, n + 1):
if dp.get(li[i], 0) == 0:
dp[li[i]] = 1
print(li[i])
```
Yes
| 49,278 | [
0.391845703125,
0.04095458984375,
0.375,
0.399169921875,
0.060699462890625,
-0.525390625,
-0.501953125,
0.358642578125,
0.282958984375,
0.26806640625,
0.494140625,
-0.11212158203125,
0.358154296875,
-0.67822265625,
-0.615234375,
-0.0235137939453125,
-0.71240234375,
-0.5537109375,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Submitted Solution:
```
n = int(input())
d = {}
for i in range(n):
d[input()] = i
a = [(i[1], i[0]) for i in d.items()]
a.sort(reverse = True)
print(*[i[1] for i in a], sep = '\n')
```
Yes
| 49,279 | [
0.409912109375,
0.0078887939453125,
0.372314453125,
0.384521484375,
0.043548583984375,
-0.481201171875,
-0.521484375,
0.386474609375,
0.27099609375,
0.28125,
0.494384765625,
-0.1370849609375,
0.35400390625,
-0.66650390625,
-0.6298828125,
-0.046478271484375,
-0.697265625,
-0.546875,... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Submitted Solution:
```
def main():
n = int(input())
friend_dict = {}
while n > 0:
s = input()
if s in friend_dict.keys():
friend_dict[s] += 1
else:
friend_dict[s] = 1
n -= 1
friend_dict = dict(sorted(friend_dict.items(), key=lambda x: x[1], reverse=True))
for friend in friend_dict.keys():
print(friend)
main()
```
No
| 49,280 | [
0.381591796875,
0.033294677734375,
0.383056640625,
0.37841796875,
0.046234130859375,
-0.4990234375,
-0.53076171875,
0.3671875,
0.305908203125,
0.278564453125,
0.42236328125,
-0.1396484375,
0.337890625,
-0.66845703125,
-0.623046875,
-0.039031982421875,
-0.74267578125,
-0.52880859375... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Submitted Solution:
```
n = int(input())
S = []
for i in range(n):
S.append(input())
R = []
for i in S:
if i in R:
R.remove(i)
R.insert(0, i)
print(R)
```
No
| 49,281 | [
0.380859375,
0.0236663818359375,
0.377197265625,
0.394287109375,
0.04779052734375,
-0.50927734375,
-0.5390625,
0.37548828125,
0.27978515625,
0.252197265625,
0.491943359375,
-0.10791015625,
0.343017578125,
-0.677734375,
-0.64794921875,
-0.0214080810546875,
-0.71337890625,
-0.5771484... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Submitted Solution:
```
n = int(input())
d = {}
for i in range(n):
s = input()
d[s] = i + 1
d = sorted(d , reverse= True, key= lambda x : x[1])
#print(d)
for i in d :
print(i)
```
No
| 49,282 | [
0.39306640625,
0.0244293212890625,
0.36572265625,
0.3876953125,
0.0447998046875,
-0.517578125,
-0.52880859375,
0.369140625,
0.288330078125,
0.26513671875,
0.482666015625,
-0.11114501953125,
0.352294921875,
-0.66552734375,
-0.638671875,
-0.04144287109375,
-0.71630859375,
-0.55712890... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
Input
The first line contains integer n (1 β€ n β€ 200 000) β the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.
Output
Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.
Examples
Input
4
alex
ivan
roman
ivan
Output
ivan
roman
alex
Input
8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina
Output
alina
maria
ekaterina
darya
Note
In the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:
1. alex
Then Polycarpus writes to friend by name "ivan" and the list looks as follows:
1. ivan
2. alex
Polycarpus writes the third message to friend by name "roman" and the list looks as follows:
1. roman
2. ivan
3. alex
Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:
1. ivan
2. roman
3. alex
Submitted Solution:
```
n=int(input())
p=[0]*n
for i in range(n):
p[i]=input()
compteur=0
for i in range(n):
if i<n-compteur-1:
if p.count(p[i])>1:
p.remove(p[i])
compteur+=1
r=len(p)
for i in range(r):
print(p[r-1-i], end="\n")
```
No
| 49,283 | [
0.40771484375,
0.043731689453125,
0.392822265625,
0.40380859375,
0.03570556640625,
-0.525390625,
-0.54052734375,
0.365478515625,
0.274658203125,
0.28759765625,
0.46923828125,
-0.0902099609375,
0.3427734375,
-0.67236328125,
-0.6396484375,
-0.0292816162109375,
-0.7177734375,
-0.56445... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is sad β New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 β€ r, g, b β€ 10^9) β the number of red, green and blue lamps in the set, respectively.
Output
Print t lines β for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Tags: math
Correct Solution:
```
t = int(input())
for _ in range(t):
r, g, b = map(int, input().split())
r, g, b = sorted([r, g, b])
print('No' if b > r+g+1 else 'Yes')
```
| 49,784 | [
0.1409912109375,
-0.296875,
-0.249755859375,
-0.0193023681640625,
-0.408447265625,
-0.3642578125,
-0.28271484375,
0.27294921875,
0.62109375,
0.890625,
0.6044921875,
-0.1370849609375,
0.1319580078125,
-0.5302734375,
-0.47607421875,
0.1868896484375,
-0.64501953125,
-0.435302734375,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is sad β New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 β€ r, g, b β€ 10^9) β the number of red, green and blue lamps in the set, respectively.
Output
Print t lines β for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Tags: math
Correct Solution:
```
T = int(input())
for i in range(T):
a,b,c = map(int, input().split(' '))
print("Yes") if b+c >= a-1 and a+c>= b-1 and b+a>=c-1 else print("No")
```
| 49,785 | [
0.16748046875,
-0.281494140625,
-0.255126953125,
-0.00991058349609375,
-0.410400390625,
-0.364990234375,
-0.24560546875,
0.27294921875,
0.5927734375,
0.89501953125,
0.623046875,
-0.12091064453125,
0.1376953125,
-0.56494140625,
-0.461669921875,
0.196044921875,
-0.63134765625,
-0.460... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is sad β New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 β€ r, g, b β€ 10^9) β the number of red, green and blue lamps in the set, respectively.
Output
Print t lines β for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Tags: math
Correct Solution:
```
def sol(l):
m = -1
idx = 0
for i in range(3):
if l[i] > m :
m = l[i]
idx = i
sum = 0
piot = 0
for i in range(3):
if idx != i :
sum += l[i]
if m - sum < 2:
return 'Yes'
return 'No'
def main():
t = int(input())
for _ in range(t):
l = list(map(int,input().split()))
print(sol(l))
main()
```
| 49,786 | [
0.168212890625,
-0.27734375,
-0.2236328125,
0.01194000244140625,
-0.42724609375,
-0.388427734375,
-0.2493896484375,
0.274658203125,
0.6064453125,
0.88525390625,
0.626953125,
-0.1229248046875,
0.10162353515625,
-0.513671875,
-0.47607421875,
0.2322998046875,
-0.66357421875,
-0.431640... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is sad β New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 β€ r, g, b β€ 10^9) β the number of red, green and blue lamps in the set, respectively.
Output
Print t lines β for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Tags: math
Correct Solution:
```
t=int(input())
for i in range(t):
p=list(map(int,input().split()))
p.sort()
if p[2]-1<=p[1]+p[0]:print('Yes')
else:
print('No')
```
| 49,789 | [
0.12841796875,
-0.283935546875,
-0.277587890625,
-0.0084991455078125,
-0.43115234375,
-0.3662109375,
-0.278564453125,
0.307373046875,
0.60791015625,
0.92724609375,
0.603515625,
-0.1268310546875,
0.1397705078125,
-0.560546875,
-0.48779296875,
0.1929931640625,
-0.62451171875,
-0.4499... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is sad β New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 β€ r, g, b β€ 10^9) β the number of red, green and blue lamps in the set, respectively.
Output
Print t lines β for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Tags: math
Correct Solution:
```
for i in range (int(input())):
r,g,b=map(int,input().split())
count=0
if(r>b+g+1):
count+=1
if(b>g+r+1):
count+=1
if(g>b+r+1):
count+=1
if(count==0):
print("YES")
else:
print("NO")
```
| 49,790 | [
0.1512451171875,
-0.283203125,
-0.2379150390625,
-0.002452850341796875,
-0.410400390625,
-0.396484375,
-0.258056640625,
0.27880859375,
0.595703125,
0.90966796875,
0.61962890625,
-0.1201171875,
0.1231689453125,
-0.54150390625,
-0.46630859375,
0.2044677734375,
-0.63671875,
-0.4482421... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 β€ t β€ min(n, 10^4) and the total number of queries is limited to 6 β
10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 β
10^4 requests totally of the following type:
* ? l r β find out the sum of all elements in positions from l to r (1 β€ l β€ r β€ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 β€ n β€ 2 β
10^5, 1 β€ t β€ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 β€ k β€ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 β
10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 β
10^4):
* ! x β position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 β€ |s| β€ 2 β
10^5), consisting of zeros and ones, and an integer t (1 β€ t β€ min(|s|, 10^4)) β hidden array and number of requests, respectively. In the next t lines output the number k (1 β€ k β€ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Tags: binary search, constructive algorithms, data structures, interactive
Correct Solution:
```
import sys
def ask_query(l, r):
print ("?", l+1, r+1)
sys.stdout.flush()
return int(input())
def check(low, mid):
return mid - low + 1 - ask_query(low, mid)
d = {}
n, t = map(int,input().split())
for nt in range(t):
k = int(input())
low = 0
high = n-1
while low<high:
mid = (low+high)//2
if (low, mid) not in d:
count = check(low, mid)
d[(low, mid)] = count
count = d[(low, mid)]
if count>=k:
high = mid
else:
k -= count
low = mid + 1
if (low, high) in d:
d[(low, high)] -= 1
print ("!", high+1)
```
| 49,908 | [
0.32568359375,
0.041107177734375,
0.047576904296875,
0.10833740234375,
-0.449951171875,
-0.64794921875,
-0.5693359375,
0.214111328125,
-0.08380126953125,
0.67529296875,
0.943359375,
-0.055908203125,
0.01253509521484375,
-0.52001953125,
-0.66455078125,
-0.0080413818359375,
-0.16186523... | 24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.