message stringlengths 2 65.1k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 0 108k | cluster float64 14 14 | __index_level_0__ int64 0 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4. | instruction | 0 | 21,575 | 14 | 43,150 |
Tags: data structures, math, number theory
Correct Solution:
```
#------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
import math
#------------------------iye ha mentos zindegi-----------------------------
class SegmentTree:
def __init__(self, data, default=0,func=lambda a,b:math.gcd(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
#-------------------------iye ha aam zindegi----------------------------------
from collections import defaultdict as dict
from bisect import bisect_left as lower_bound
from bisect import bisect_right as upper_bound
store = dict(list)
def findFrequency(arr, n, left, right, element):
a = lower_bound(store[element], left)
b = upper_bound(store[element], right)
return b - a
n=int(input())
l=list(map(int,input().split()))
for i in range(n):
store[l[i]].append(i + 1)
t=int(input())
st=SegmentTree(l)
d=dict()
for i in range(n):
if l[i] not in d:
d.update({l[i]:1})
else:
d[l[i]]+=1
for i in range(t):
l1,r=map(int,input().split())
g=st.query(l1-1,r-1)
#print(g)
c=findFrequency(l,n,l1,r,g)
print(r-l1+1-c)
``` | output | 1 | 21,575 | 14 | 43,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4. | instruction | 0 | 21,576 | 14 | 43,152 |
Tags: data structures, math, number theory
Correct Solution:
```
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from math import gcd
def myFun(a,b):
if a[0]<b[0]:
return a[:]
elif b[0]<a[0]:
return b[:]
else:
return [a[0],a[1]+b[1]]
class SegmentTree1:
def __init__(self, data, default=1e10, func=myFun):
"""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,1] for i in range (2*_size)]
for i in range (_size, _size + self._len):
self.data[i] = [data[i-_size],1]
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = [self._default,0]
cnt = 0
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)
class SegmentTree2:
def __init__(self, data, default=0, func=gcd):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = -1
while start < stop:
if start & 1:
if res_left==-1:
res_left = self.data[start]
else:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
if res_right == -1:
res_right = self.data[stop]
else:
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
if res_left == -1:
return res_right
elif res_right == -1:
return res_left
else:
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
n = int(input())
a = [int(i) for i in input().split()]
q = int(input())
st1 = SegmentTree1(a)
st2 = SegmentTree2(a)
for _ in range (q):
l,r = [int(i)-1 for i in input().split()]
m,cnt = st1.query(l,r+1)
g = st2.query(l,r+1)
if m==g:
print(r-l+1-cnt)
else:
print(r-l+1)
``` | output | 1 | 21,576 | 14 | 43,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4. | instruction | 0 | 21,577 | 14 | 43,154 |
Tags: data structures, math, number theory
Correct Solution:
```
import sys,os,io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_left , bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')
#for deep recursion__________________________________________-
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,p - 2, p)) % p
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
c = dict(Counter(l))
return list(set(l))
# return c
def power(x, y, p) :
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
#____________________GetPrimeFactors in log(n)________________________________________
def sieveForSmallestPrimeFactor():
MAXN = 100001
spf = [0 for i in range(MAXN)]
spf[1] = 1
for i in range(2, MAXN):
spf[i] = i
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, math.ceil(math.sqrt(MAXN))):
if (spf[i] == i):
for j in range(i * i, MAXN, i):
if (spf[j] == j):
spf[j] = i
return spf
def getPrimeFactorizationLOGN(x):
spf = sieveForSmallestPrimeFactor()
ret = list()
while (x != 1):
ret.append(spf[x])
x = x // spf[x]
return ret
#____________________________________________________________
def SieveOfEratosthenes(n):
#time complexity = nlog(log(n))
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
def si():
return input()
def divideCeil(n,x):
if (n%x==0):
return n//x
return n//x+1
def ii():
return int(input())
def li():
return list(map(int,input().split()))
#__________________________TEMPLATE__________________OVER_______________________________________________________
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
else:
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
class SegmentTree:
def __init__(self, data, default=0, func=gcd):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""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 = ii()
s = li()
d = defaultdict(lambda:[])
for i in range(n):
d[s[i]].append(i)
def cnt(x,left,right):
l = bisect_left(d[x],left)
r = bisect_right(d[x],right)
return r-l
seg = SegmentTree(s)
for i in range(ii()):
l,r = li()
l-=1
r-=1
g = seg.query(l,r+1)
print(r-l+1-cnt(g,l,r))
# def solve():
# t = 1
# t = ii()
# for _ in range(t):
# solve()
``` | output | 1 | 21,577 | 14 | 43,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little W and Little P decided to send letters to each other regarding the most important events during a day. There are n events during a day: at time moment t_i something happens to the person p_i (p_i is either W or P, denoting Little W and Little P, respectively), so he needs to immediately send a letter to the other person. They can send a letter using one of the two ways:
* Ask Friendly O to deliver the letter directly. Friendly O takes d acorns for each letter.
* Leave the letter at Wise R's den. Wise R values free space, so he takes c ⋅ T acorns for storing a letter for a time segment of length T. The recipient can take a letter from Wise R either when he leaves his own letter at Wise R's den, or at time moment t_{n + 1}, when everybody comes to Wise R for a tea. It is not possible to take a letter from Wise R's den at other time moments. The friends can store as many letters at Wise R's den as they want, paying for each one separately.
Help the friends determine the minimum possible total cost of sending all letters.
Input
The first line contains three integers n, c, d (1 ≤ n ≤ 10^5, 1 ≤ c ≤ 10^2, 1 ≤ d ≤ 10^8) — the number of letters, the cost of storing a letter for one time unit at Wise R's den and the cost of delivering a letter via Friendly O.
The next n describe the events. The i-th of them contains an integer t_i and a character p_i (0 ≤ t_i ≤ 10^6, p_i is either W or P) — the time the i-th event happens and the person the event happens to.
The last line contains a single integer t_{n + 1} (0 ≤ t_{n+1} ≤ 10^6) — the time when everybody comes to Wise R for a tea and takes all remaining letters.
It is guaranteed that t_i < t_{i + 1} for all i from 1 to n.
Output
Print a single integer — the minimum possible cost of delivery of all letters.
Examples
Input
5 1 4
0 P
1 W
3 P
5 P
8 P
10
Output
16
Input
10 10 94
17 W
20 W
28 W
48 W
51 P
52 W
56 W
62 P
75 P
78 P
87
Output
916
Note
One of optimal solutions in the first example:
* At time moment 0 Little P leaves the letter at Wise R's den.
* At time moment 1 Little W leaves his letter at Wise R's den and takes Little P's letter. This letter is at the den from time moment 0 to time moment 1, it costs 1 acorn.
* At time moment 3 Little P sends his letter via Friendly O, it costs 4 acorns.
* At time moment 5 Little P leaves his letter at the den, receiving Little W's letter which storage costs 4 acorns.
* At time moment 8 Little P leaves one more letter at the den.
* At time moment 10 Little W comes to the den for a tea and receives the two letters, paying 5 and 2 acorns.
The total cost of delivery is thus 1 + 4 + 4 + 5 + 2 = 16 acorns.
Submitted Solution:
```
N = int(1e5+5)
t=[0]*N
ch=[0]*N
n,c,d=map(int,input().split())
for i in range(1,n+1):
a,b=map(str,input().split())
t[i]=int(a)
ch[i]=b
t[n+1]=int(input())
ans=d*n
tot=0
L=t[n+1]
for i in range(n-1,1,-1):
if ch[i]==ch[i-1]:
tot+=min(d,(L-t[i])*c)
else:
tot+=(L-t[i])*c
L=t[i]
ans=min(ans,tot+d*(i-1))
print(ans)
``` | instruction | 0 | 22,067 | 14 | 44,134 |
No | output | 1 | 22,067 | 14 | 44,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications. | instruction | 0 | 22,158 | 14 | 44,316 |
Tags: data structures, greedy, sortings
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from heapq import *
def main():
n = int(input())
lst = [(a,b)for a,b in zip(map(int,input().split()),map(int,input().split()))]
lst.sort(key=lambda xx:xx[0])
heap = []
i,ans,su = 0,0,0
while i != n:
j,st = i,lst[max(0,i-1)][0]
ans += su*(lst[i][0]-st)
for x in range(lst[i][0]-st):
if not len(heap):
break
r = heappop(heap)
su += r
ans += r*(lst[i][0]-x-st)
while i != n and lst[i][0] == lst[j][0]:
su += lst[i][1]
heappush(heap,-lst[i][1])
i += 1
cou = 0
while len(heap):
ans -= cou*heappop(heap)
cou += 1
print(ans)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | output | 1 | 22,158 | 14 | 44,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications. | instruction | 0 | 22,159 | 14 | 44,318 |
Tags: data structures, greedy, sortings
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
mod=10**9+7
from heapq import*
n=int(input())
d=defaultdict(list)
a=list(map(int,input().split()))
t=list(map(int,input().split()))
ans=0
for i in range(n):
heappush(d[a[i]],t[i])
key_heap=list(d.keys())
heapify(key_heap)
s=0
m_heap=[]
while len(key_heap)>0:
k=heappop(key_heap)
s+=sum(d[k])
while len(d[k])>0:
y=heappop(d[k])
heappush(m_heap,-y)
t=heappop(m_heap)
s+=t
ans+=s
if s!=0 and k+1 not in d.keys():
heappush(key_heap,k+1)
del d[k]
print(ans)
``` | output | 1 | 22,159 | 14 | 44,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications. | instruction | 0 | 22,160 | 14 | 44,320 |
Tags: data structures, greedy, sortings
Correct Solution:
```
import os,io
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import heapq
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
ua = len(set(a))
if ua == n:
print(0)
else:
d = {}
for i in range(n):
if a[i] in d:
d[a[i]].append((-t[i],a[i]))
else:
d[a[i]] = [(-t[i],a[i])]
for i in d:
heapq.heapify(d[i])
keys = list(d.keys())
heapq.heapify(keys)
cost = 0
int_heap = []
while keys:
# print(d)
# print(keys,int_heap)
key = heapq.heappop(keys)
vals = []
if key in d:
vals = d[key]
del d[key]
if int_heap and vals:
maxval1,parent1 = heapq.heappop(vals)
maxval2,parent2 = heapq.heappop(int_heap)
if maxval2<maxval1:
cost += (-maxval2) * (key - parent2)
heapq.heappush(vals,(maxval1,parent1))
else:
cost += (-maxval1) * (key - parent1)
heapq.heappush(int_heap,(maxval2, parent2))
elif vals:
maxval1, parent1 = heapq.heappop(vals)
cost += (-maxval1) * (key - parent1)
elif int_heap:
maxval2, parent2 = heapq.heappop(int_heap)
cost += (-maxval2) * (key - parent2)
if (vals or int_heap) and (key+1 not in d):
heapq.heappush(keys,key+1)
while vals:
heapq.heappush(int_heap,vals.pop())
# print(key, cost)
print(cost)
``` | output | 1 | 22,160 | 14 | 44,321 |
Provide tags and a correct Python 3 solution for this coding contest problem.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications. | instruction | 0 | 22,161 | 14 | 44,322 |
Tags: data structures, greedy, sortings
Correct Solution:
```
"""
Author - Satwik Tiwari .
27th Oct , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
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
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 graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for pp in range(t):
solve(pp)
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(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
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
def bucketsort(order, seq):
buckets = [0] * (max(seq) + 1)
for x in seq:
buckets[x] += 1
for i in range(len(buckets) - 1):
buckets[i + 1] += buckets[i]
new_order = [-1] * len(seq)
for i in reversed(order):
x = seq[i]
idx = buckets[x] = buckets[x] - 1
new_order[idx] = i
return new_order
def ordersort(order, seq, reverse=False):
bit = max(seq).bit_length() >> 1
mask = (1 << bit) - 1
order = bucketsort(order, [x & mask for x in seq])
order = bucketsort(order, [x >> bit for x in seq])
if reverse:
order.reverse()
return order
def long_ordersort(order, seq):
order = ordersort(order, [int(i & 0x7fffffff) for i in seq])
return ordersort(order, [int(i >> 31) for i in seq])
def multikey_ordersort(order, *seqs, sort=ordersort):
for i in reversed(range(len(seqs))):
order = sort(order, seqs[i])
return order
#for pair like (l,r) make array of l and r separately
# l = []
# r = []
# for i in range(10):
# l.append(2)
# if(i%2==1):
# r.append(i+1)
# else:
# r.append(i-1)
#
# #pass it like this. if req triplet make on more like above.
#
# ans = multikey_ordersort(range(10),l,r)
#return indexes of sorted order. build list of tupples if you want.
def solve(case):
n = int(inp())
l = lis()
r = lis()
order = multikey_ordersort(range(n),l,r)
sl = []
for i in order:
sl.append((l[i],r[i]))
ans = 0
currsum = 0
h = []
for i in range(0,n):
temp = sl[i][0] - sl[i-1][0]
# print(temp,h,currsum,ans)
for j in range(temp):
if(len(h) != 0):
curr = -heappop(h)
currsum-=curr
ans+=currsum
else:
break
heappush(h,-sl[i][1])
currsum+=sl[i][1]
while(len(h)!=0):
curr = -heappop(h)
currsum-=curr
ans+=currsum
print(ans)
testcase(1)
# testcase(int(inp()))
``` | output | 1 | 22,161 | 14 | 44,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications. | instruction | 0 | 22,162 | 14 | 44,324 |
Tags: data structures, greedy, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
raw1 = list(map(int,input().split()))
raw2 = list(map(int,input().split()))
c = []
for i in range(n):
c.append((raw1[i],raw2[i]))
c.sort()
c.append((10**12,0))
#print(c)
import heapq
ans = 0
last = 0
now = []
for x in c:
a,t = x
for ai in range(last,a):
if not now:
break
tm,am = heapq.heappop(now)
tm = 10**5-tm
ans += (ai-am) * tm
#print(ai-am,tm)
heapq.heappush(now,(10**5-t,a))
last = a
#print(ans,now)
#print(ans,now)
print(ans)
``` | output | 1 | 22,162 | 14 | 44,325 |
Provide tags and a correct Python 3 solution for this coding contest problem.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications. | instruction | 0 | 22,163 | 14 | 44,326 |
Tags: data structures, greedy, sortings
Correct Solution:
```
from heapq import *
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def main():
n=II()
aa=LI()
tt=LI()
at=[(a,t) for a,t in zip(aa,tt)]
heapify(at)
pen=[]
a=0
s=0
ans=0
while pen or at:
while not pen or (at and at[0][0]==a):
na,nt=heappop(at)
heappush(pen,-nt)
a=na
s+=nt
t=-heappop(pen)
s-=t
ans+=s
a+=1
print(ans)
main()
``` | output | 1 | 22,163 | 14 | 44,327 |
Provide tags and a correct Python 3 solution for this coding contest problem.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications. | instruction | 0 | 22,164 | 14 | 44,328 |
Tags: data structures, greedy, sortings
Correct Solution:
```
import heapq
from collections import defaultdict
def solve(N, A, T):
# Find conflicting nums
numToConflicts = defaultdict(list)
for i, x in enumerate(A):
numToConflicts[x].append(i)
# Iterate the conflict nums in heap since possible nums is in 10**9
# Pick the best to keep for each num, all other conflicts get scooted forward in another heap
conflictNums = list(numToConflicts.keys())
heapq.heapify(conflictNums)
scoot = []
assigned = 0
cost = 0
while assigned != N:
num = heapq.heappop(conflictNums)
heapCost = float("-inf")
if scoot:
heapCost, fromNum = scoot[0]
heapCost *= -1
conflictCost = float("-inf")
indices = []
if num in numToConflicts:
indices = numToConflicts[num]
maxIndex = max(indices, key=lambda i: T[i])
conflictCost = T[maxIndex]
# Pick costliest from conflicts or heap
if heapCost > conflictCost:
# Use the heap for this cell
heapq.heappop(scoot)
cost += (num - fromNum) * heapCost
else:
# Use the costliest of the existing indices for this cell
indices = filter(lambda x: x != maxIndex, indices)
assigned += 1
# Scoot everything else into the heap
for i in indices:
heapq.heappush(scoot, (-T[i], num))
# If there's something being scooted, make sure the next num is num + 1
if scoot and (not conflictNums or conflictNums[0] != num + 1):
heapq.heappush(conflictNums, num + 1)
return cost
if __name__ == "__main__":
N, = map(int, input().split())
A = [int(x) for x in input().split()]
T = [int(x) for x in input().split()]
ans = solve(N, A, T)
print(ans)
``` | output | 1 | 22,164 | 14 | 44,329 |
Provide tags and a correct Python 3 solution for this coding contest problem.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications. | instruction | 0 | 22,165 | 14 | 44,330 |
Tags: data structures, greedy, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
import heapq
n = int(input())
x = list(map(int, input().split()))
t = list(map(int, input().split()))
a = []
M = 1000000
for i in range(n):
a.append(x[i] * M + t[i])
a.sort()
i = 0
ans = 0
while i < n:
xi, ti = divmod(a[i], M)
j = i + 1
while j < n:
xj, tj = divmod(a[j], M)
b = j - i + xi
if xj >= b:
break
j += 1
j -= 1
if i < j:
b = []
ptr = i
for target in range(xi, j - i + xi + 1):
while ptr <= j:
xp, tp = divmod(a[ptr], M)
if xp <= target:
heapq.heappush(b, (-tp, xp))
else:
break
ptr += 1
tp, xp = heapq.heappop(b)
ans += -tp * (target - xp)
i = j + 1
print(ans)
``` | output | 1 | 22,165 | 14 | 44,331 |
Provide tags and a correct Python 2 solution for this coding contest problem.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications. | instruction | 0 | 22,166 | 14 | 44,332 |
Tags: data structures, greedy, sortings
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
n=ni()
l1=li()
l2=li()
l=[(i,j) for i,j in zip(l1,l2)]
l.sort(key=lambda x:(-x[1],x[0]))
ans=0
d=Counter()
for i,j in l:
curr=i
stk=[]
while d[curr]:
stk.append(curr)
curr=d[curr]
d[curr]=curr+1
while stk:
d[stk.pop()]=curr+1
ans+=j*(curr-i)
pn(ans)
``` | output | 1 | 22,166 | 14 | 44,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications.
Submitted Solution:
```
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
n=int(input())
l=list(map(int,input().split()))
l1=list(map(int,input().split()))
l=sort_list(l,l1)
l.reverse()
l1.sort(reverse=True)
f=set()
nextq=dict()
ans=0
def nex(i):
if nextq[i] in f:
nextq[i]=nex(nextq[i])
return nextq[i]
for i in range(n):
if l[i] in f:
d=nex(l[i])
ans+=(d-l[i])*l1[i]
f.add(d)
nextq.update({d:d+1})
else:
f.add(l[i])
nextq.update({l[i]:l[i]+1})
print(ans)
``` | instruction | 0 | 22,167 | 14 | 44,334 |
Yes | output | 1 | 22,167 | 14 | 44,335 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications.
Submitted Solution:
```
from collections import defaultdict
from heapq import heappop, heappush, heapify
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
d = defaultdict(list)
for i in range(n):
d[a[i]].append(t[i])
heap2 = list(set(a))
heapify(heap2)
ans = 0
used = set()
heap = []
s = 0
while heap2:
cur = heappop(heap2)
if cur in used:
continue
used.add(cur)
for ti in d[cur]:
heappush(heap, -ti)
s += ti
ti = -heappop(heap)
s -= ti
ans += s
if heap:
heappush(heap2, cur + 1)
print(ans)
``` | instruction | 0 | 22,168 | 14 | 44,336 |
Yes | output | 1 | 22,168 | 14 | 44,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications.
Submitted Solution:
```
import sys
input = sys.stdin.readline
out = sys.stdout
from heapq import*
from collections import defaultdict
n=int(input())
d=defaultdict(list)
a=list(map(int,input().split()))
t=list(map(int,input().split()))
ans=0
for i in range(n):
heappush(d[a[i]],t[i])
key_heap=list(d.keys())
heapify(key_heap)
s=0
m_heap=[]
while len(key_heap)>0:
k=heappop(key_heap)
s+=sum(d[k])
while len(d[k])>0:
y=heappop(d[k])
heappush(m_heap,-y)
t=heappop(m_heap)
s+=t
ans+=s
if s!=0 and k+1 not in d.keys():
heappush(key_heap,k+1)
del d[k]
out.write(str(ans)+'\n')
``` | instruction | 0 | 22,169 | 14 | 44,338 |
Yes | output | 1 | 22,169 | 14 | 44,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications.
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi, ceil, log, inf
from itertools import permutations
from copy import deepcopy
from heapq import *
from sys import setrecursionlimit
class Data:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value[0]>other.value[0] or (self.value[0]==other.value[0] and self.value[1]<other.value[1])
def main():
n = int(input())
a = list(map(int, input().split()))
b=defaultdict(list)
for i,v in enumerate(input().split()):
b[a[i]].append(int(v))
c=[]
for i in b:
c.append(i)
c.sort()
h=[]
heapify(h)
m=len(c)
t=0
for i in range(m):
for j in range(len(b[c[i]])):
heappush(h, Data((b[c[i]][j],c[i])))
z=heappop(h).value
if z[1]!=c[i]:
t+=(c[i]-z[1])*z[0]
if i+1<m:
if c[i] + 1!=c[i + 1]:
for j in range(c[i]+1,min(c[i+1],c[i]+len(h)+1)):
z=heappop(h).value
t+=(j-z[1])*z[0]
else:
for j in range(c[i]+1,c[i]+len(h)+1):
z = heappop(h).value
t += (j-z[1])*z[0]
print(t)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 22,170 | 14 | 44,340 |
Yes | output | 1 | 22,170 | 14 | 44,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
sa = sorted([(a[i], t[i]) for i in range(n)]) + [(10**10, 0)]
# print(sa)
la, count = 0, 0
mt = float('inf')
res = 0
for ai, ti in sa:
# print(ai, ti, la, mt, count)
if la < ai:
if count > 1:
count = 1
res += mt
else:
count = 0
mt = float('inf')
mt = min(mt, ti)
count += 1
la = ai
print(res)
``` | instruction | 0 | 22,171 | 14 | 44,342 |
No | output | 1 | 22,171 | 14 | 44,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications.
Submitted Solution:
```
import heapq
n=int(input())
a=list(map(int,input().split()))
t=list(map(int,input().split()))
d={}
mxm={}
sm={}
mxm2={}
for i in range(len(a)):
if a[i] in mxm:
if t[i]>=mxm[a[i]]:
mxm2[a[i]]=mxm[a[i]]
mxm[a[i]]=t[i]
else:
mxm2[a[i]]=max(mxm2.get(a[i],0),t[i])
else:
mxm[a[i]]=t[i]
if a[i] not in d:
d[a[i]]=0
sm[a[i]]=sm.get(a[i],0)+t[i]
d[a[i]]+=1
k=list(d.keys())
heapq.heapify(k)
cost=0
while len(k)>0:
key=heapq.heappop(k)
if d[key]<=1:
continue
new_key=key+1
heapq.heappush(k,new_key)
cost+=sm[key]-mxm[key]
sm[new_key]=sm.get(new_key,0)+sm[key]-mxm[key]
d[new_key]=d.get(new_key,0)+d[key]-1
d[key]=1
# we need to update mxm and mxm2 now
if new_key in mxm2:
v1=mxm[new_key]
v2=mxm2[new_key]
v3=mxm2[key]
mxm[new_key]=max(v1,v2,v3)
if mxm[new_key]==v1:
mxm2[new_key]=max(v2,v3)
elif mxm[new_key]==v2:
mxm2[new_key]=max(v1,v3)
elif mxm[new_key]==v3:
mxm2[new_key]=max(v2,v1)
elif new_key in mxm:
v1=mxm[new_key]
v2=mxm2[key]
mxm[new_key]=max(v1,v2)
mxm2[new_key]=min(v1,v2)
else:
mxm[new_key]=mxm2.get(key,0)
mxm2[new_key]=0
print(cost)
``` | instruction | 0 | 22,172 | 14 | 44,344 |
No | output | 1 | 22,172 | 14 | 44,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications.
Submitted Solution:
```
n = int(input())
a = input().split()
a = [int(i) for i in a]
t = input().split()
t = [int(i) for i in t]
a,t = (list(x) for x in zip(*sorted(zip(a, t), key=lambda x: (x[0],x[1]))))
# b = a
# u = t
total = 0
# while len(b) > 1:
# change = False
# print(b)
# for i in range(len(b)-1):
# if b[i] == b[i+1]:
# print(b[i])
# total += u[i]
# b = b[i+1:]
# u = u[i+1:]
# change = True
# break
# if change is False:
# break
# print(total)
b = sorted(list(dict.fromkeys(a)))
mynos = {}
maxnos = {}
sumnos = {}
for ind, elem in enumerate(a):
if elem not in mynos:
mynos[elem] = [t[ind]]
maxnos[elem] = t[ind]
sumnos[elem] = 0
else:
mynos[elem].append(t[ind])
if t[ind] > maxnos[elem]:
sumnos[elem] += maxnos[elem]
maxnos[elem] = t[ind]
else:
sumnos[elem] += t[ind]
c = b
while c:
if len(c) == 1 and len(mynos[c[0]]) == 1:
break
complete = False
for ind,no in enumerate(c):
new = False
if len(mynos[no]) > 1:
continued = False
for i in mynos[no]:
if i == maxnos[no] and continued is False:
continued = True
continue
total += i
if no+1 not in mynos:
mynos[no+1] = [i]
maxnos[no+1] = i
sumnos[no+1] = 0
new = True
d = [no+1] + c[ind+1:]
else:
mynos[no+1].append(i)
if i > maxnos[no+1]:
sumnos[no+1] += maxnos[no+1]
maxnos[no+1] = i
else:
sumnos[no+1] += i
if new is True:
c = d
break
else:
complete = True
if complete is True:
break
print(total)
# get same size categories
# 5
# 3 7 9 7 8
# 5 2 5 7 5
# 3 7 7 8 9
# 5 2 7 5 5
# try:
# raise Exception
# except:
# print("-1")
# thenos.sort(key=lambda x: x[2], reverse=True)
# int(math.log(max(numbers)+1,2))
# 2**3 (power)
``` | instruction | 0 | 22,173 | 14 | 44,346 |
No | output | 1 | 22,173 | 14 | 44,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
Input
The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).
The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).
The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).
Output
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
Examples
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
Note
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int,input().split()))
t = list(map(int,input().split()))
ls = list(zip(a,t))
ls.sort()
ls.append((10**18,0))
ist = 0
xst = ls[0][0]
anstmp = []
flg = 0
ans = 0
minlist = [ls[0]]
for i in range(1,n+1):
if i-ist <= ls[i][0]-xst:
flg = 1
ist = i
xst = ls[i][0]
if flg == 0:
if ls[i][0] == xst:
minlist.append(ls[i])
else:
anstmp.append(ls[i])
else:
flg = 0
anstmp.extend(minlist[:-1])
if not anstmp:
anstmp = []
minlist = [ls[i]]
continue
mn = minlist[0][0]
l = len(anstmp)
mx = mn+l
anstmp.sort(key = lambda x:x[1])
for j in range(l):
ans += anstmp[j][1]*(mx-anstmp[j][0]-j)
anstmp = []
minlist = [ls[i]]
print(ans)
``` | instruction | 0 | 22,174 | 14 | 44,348 |
No | output | 1 | 22,174 | 14 | 44,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, 8, 4, 4] is stable (because 4 - 1 ≤ x, 4 - 4 ≤ x, 8 - 4 ≤ x, 10 - 8 ≤ x), while the group with levels [2, 10, 10, 7] is not stable (7 - 2 = 5 > x).
Apart from the n given students, teachers can invite at most k additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).
For example, if there are two students with levels 1 and 5; x = 2; and k ≥ 1, then you can invite a new student with level 3 and put all the students in one stable group.
Input
The first line contains three integers n, k, x (1 ≤ n ≤ 200 000, 0 ≤ k ≤ 10^{18}, 1 ≤ x ≤ 10^{18}) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}) — the students levels.
Output
In the only line print a single integer: the minimum number of stable groups you can split the students into.
Examples
Input
8 2 3
1 1 5 8 12 13 20 22
Output
2
Input
13 0 37
20 20 80 70 70 70 420 5 1 5 1 60 90
Output
3
Note
In the first example you can invite two students with levels 2 and 11. Then you can split the students into two stable groups:
1. [1, 1, 2, 5, 8, 11, 12, 13],
2. [20, 22].
In the second example you are not allowed to invite new students, so you need 3 groups:
1. [1, 1, 5, 5, 20, 20]
2. [60, 70, 70, 70, 80, 90]
3. [420] | instruction | 0 | 22,293 | 14 | 44,586 |
Tags: greedy, sortings
Correct Solution:
```
"""
from sys import stdin, stdout
import math
from functools import reduce
import statistics
import numpy as np
import itertools
import operator
from sys import stdin, stdout
import math
from functools import reduce
import statistics
import numpy as np
import itertools
import sys
import operator
from collections import Counter
import decimal
"""
import math
import os
import sys
from math import ceil, floor, sqrt, gcd, factorial
from io import BytesIO, IOBase
from collections import Counter
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def prog_name():
n, k, d = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
cnt = 1
diff_l = []
for x in range(n - 1):
if l[x + 1] - l[x] > d:
cnt += 1
if (l[x + 1] - l[x] ) % d == 0:
diff_l.append(((l[x + 1] - l[x]) // d) - 1)
else:
# diff_l.append(math.floor((l[x + 1] - l[x]) / d))
diff_l.append((l[x + 1] - l[x]) // d)
diff_l.sort()
for y in diff_l:
if k - y >= 0:
k -= y
cnt -= 1
else:
break
print(cnt)
def main():
# init = time()
T = 1
for unique in range(T):
# print("Case #"+str(unique+1)+":",end = " ")
prog_name()
# print(time() - init)
if __name__ == "__main__":
main()
``` | output | 1 | 22,293 | 14 | 44,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, 8, 4, 4] is stable (because 4 - 1 ≤ x, 4 - 4 ≤ x, 8 - 4 ≤ x, 10 - 8 ≤ x), while the group with levels [2, 10, 10, 7] is not stable (7 - 2 = 5 > x).
Apart from the n given students, teachers can invite at most k additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).
For example, if there are two students with levels 1 and 5; x = 2; and k ≥ 1, then you can invite a new student with level 3 and put all the students in one stable group.
Input
The first line contains three integers n, k, x (1 ≤ n ≤ 200 000, 0 ≤ k ≤ 10^{18}, 1 ≤ x ≤ 10^{18}) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}) — the students levels.
Output
In the only line print a single integer: the minimum number of stable groups you can split the students into.
Examples
Input
8 2 3
1 1 5 8 12 13 20 22
Output
2
Input
13 0 37
20 20 80 70 70 70 420 5 1 5 1 60 90
Output
3
Note
In the first example you can invite two students with levels 2 and 11. Then you can split the students into two stable groups:
1. [1, 1, 2, 5, 8, 11, 12, 13],
2. [20, 22].
In the second example you are not allowed to invite new students, so you need 3 groups:
1. [1, 1, 5, 5, 20, 20]
2. [60, 70, 70, 70, 80, 90]
3. [420] | instruction | 0 | 22,294 | 14 | 44,588 |
Tags: greedy, sortings
Correct Solution:
```
if __name__=="__main__":
n,k,x=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
li=[]
for i in range(1,n):
if a[i]-a[i-1]>x:
li.append(a[i]-a[i-1])
li.sort()
i=0
l=len(li)
c=l
while k>0 and i<l:
if li[i]%x==0:
t=(li[i]//x)-1
else:
t=li[i]//x
k-=t
if k>=0:
c-=1
i+=1
print(c+1)
``` | output | 1 | 22,294 | 14 | 44,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, 8, 4, 4] is stable (because 4 - 1 ≤ x, 4 - 4 ≤ x, 8 - 4 ≤ x, 10 - 8 ≤ x), while the group with levels [2, 10, 10, 7] is not stable (7 - 2 = 5 > x).
Apart from the n given students, teachers can invite at most k additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).
For example, if there are two students with levels 1 and 5; x = 2; and k ≥ 1, then you can invite a new student with level 3 and put all the students in one stable group.
Input
The first line contains three integers n, k, x (1 ≤ n ≤ 200 000, 0 ≤ k ≤ 10^{18}, 1 ≤ x ≤ 10^{18}) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}) — the students levels.
Output
In the only line print a single integer: the minimum number of stable groups you can split the students into.
Examples
Input
8 2 3
1 1 5 8 12 13 20 22
Output
2
Input
13 0 37
20 20 80 70 70 70 420 5 1 5 1 60 90
Output
3
Note
In the first example you can invite two students with levels 2 and 11. Then you can split the students into two stable groups:
1. [1, 1, 2, 5, 8, 11, 12, 13],
2. [20, 22].
In the second example you are not allowed to invite new students, so you need 3 groups:
1. [1, 1, 5, 5, 20, 20]
2. [60, 70, 70, 70, 80, 90]
3. [420] | instruction | 0 | 22,295 | 14 | 44,590 |
Tags: greedy, sortings
Correct Solution:
```
import sys,math
from collections import deque,defaultdict
import operator as op
from functools import reduce
from itertools import permutations
import heapq
#sys.setrecursionlimit(10**7)
# OneDrive\Documents\codeforces
I=sys.stdin.readline
alpha="abcdefghijklmnopqrstuvwxyz"
mod=10**9 + 7
"""
x_move=[-1,0,1,0,-1,1,1,-1]
y_move=[0,1,0,-1,1,1,-1,-1]
"""
def ii():
return int(I().strip())
def li():
return list(map(int,I().strip().split()))
def mi():
return map(int,I().strip().split())
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom
def ispali(s):
i=0
j=len(s)-1
while i<j:
if s[i]!=s[j]:
return False
i+=1
j-=1
return True
def isPrime(n):
if n<=1:
return False
elif n<=2:
return True
else:
for i in range(2,int(n**.5)+1):
if n%i==0:
return False
return True
def main():
n,k,x=mi()
arr=sorted(li())
tmp=[]
last=arr[0]
for i in range(1,n):
if arr[i]-last>x:
tmp.append(arr[i]-last-1)
last=arr[i]
tmp.sort()
ntmp=len(tmp)
for i in tmp:
needk=math.floor(i//x)
if k>=needk:
ntmp-=1
k-=needk
print(ntmp+1)
if __name__ == '__main__':
main()
``` | output | 1 | 22,295 | 14 | 44,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, 8, 4, 4] is stable (because 4 - 1 ≤ x, 4 - 4 ≤ x, 8 - 4 ≤ x, 10 - 8 ≤ x), while the group with levels [2, 10, 10, 7] is not stable (7 - 2 = 5 > x).
Apart from the n given students, teachers can invite at most k additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).
For example, if there are two students with levels 1 and 5; x = 2; and k ≥ 1, then you can invite a new student with level 3 and put all the students in one stable group.
Input
The first line contains three integers n, k, x (1 ≤ n ≤ 200 000, 0 ≤ k ≤ 10^{18}, 1 ≤ x ≤ 10^{18}) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}) — the students levels.
Output
In the only line print a single integer: the minimum number of stable groups you can split the students into.
Examples
Input
8 2 3
1 1 5 8 12 13 20 22
Output
2
Input
13 0 37
20 20 80 70 70 70 420 5 1 5 1 60 90
Output
3
Note
In the first example you can invite two students with levels 2 and 11. Then you can split the students into two stable groups:
1. [1, 1, 2, 5, 8, 11, 12, 13],
2. [20, 22].
In the second example you are not allowed to invite new students, so you need 3 groups:
1. [1, 1, 5, 5, 20, 20]
2. [60, 70, 70, 70, 80, 90]
3. [420] | instruction | 0 | 22,296 | 14 | 44,592 |
Tags: greedy, sortings
Correct Solution:
```
n,k,x =list(map(int ,input().split()))
arr = list(map(int ,input().split()))
arr.sort()
groups =1
re = []
for i in range(n-1):
diff = arr[i+1]-arr[i]
if diff>x :
if x==0:
groups+=1
continue
if diff%x==0:
diff = diff//x -1
else:
diff =diff//x
re.append(diff)
groups+=1
re.sort()
for i in range(len(re)):
k-=re[i]
if k>=0:
groups-=1
else:
break
print(groups)
``` | output | 1 | 22,296 | 14 | 44,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, 8, 4, 4] is stable (because 4 - 1 ≤ x, 4 - 4 ≤ x, 8 - 4 ≤ x, 10 - 8 ≤ x), while the group with levels [2, 10, 10, 7] is not stable (7 - 2 = 5 > x).
Apart from the n given students, teachers can invite at most k additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).
For example, if there are two students with levels 1 and 5; x = 2; and k ≥ 1, then you can invite a new student with level 3 and put all the students in one stable group.
Input
The first line contains three integers n, k, x (1 ≤ n ≤ 200 000, 0 ≤ k ≤ 10^{18}, 1 ≤ x ≤ 10^{18}) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}) — the students levels.
Output
In the only line print a single integer: the minimum number of stable groups you can split the students into.
Examples
Input
8 2 3
1 1 5 8 12 13 20 22
Output
2
Input
13 0 37
20 20 80 70 70 70 420 5 1 5 1 60 90
Output
3
Note
In the first example you can invite two students with levels 2 and 11. Then you can split the students into two stable groups:
1. [1, 1, 2, 5, 8, 11, 12, 13],
2. [20, 22].
In the second example you are not allowed to invite new students, so you need 3 groups:
1. [1, 1, 5, 5, 20, 20]
2. [60, 70, 70, 70, 80, 90]
3. [420] | instruction | 0 | 22,297 | 14 | 44,594 |
Tags: greedy, sortings
Correct Solution:
```
n,k,x = map(int,input().split())
v = list(map(int,input().split()))
v.sort()
w = []
for i in range(n-1):
dif = max((v[i+1]-v[i]-1)//x,0)
w.append(dif)
w.sort()
aux = 0
res = n
for i in range(len(w)):
aux+=w[i]
if aux>k:
res = i
break
print(max(n-res,1))
``` | output | 1 | 22,297 | 14 | 44,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, 8, 4, 4] is stable (because 4 - 1 ≤ x, 4 - 4 ≤ x, 8 - 4 ≤ x, 10 - 8 ≤ x), while the group with levels [2, 10, 10, 7] is not stable (7 - 2 = 5 > x).
Apart from the n given students, teachers can invite at most k additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).
For example, if there are two students with levels 1 and 5; x = 2; and k ≥ 1, then you can invite a new student with level 3 and put all the students in one stable group.
Input
The first line contains three integers n, k, x (1 ≤ n ≤ 200 000, 0 ≤ k ≤ 10^{18}, 1 ≤ x ≤ 10^{18}) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}) — the students levels.
Output
In the only line print a single integer: the minimum number of stable groups you can split the students into.
Examples
Input
8 2 3
1 1 5 8 12 13 20 22
Output
2
Input
13 0 37
20 20 80 70 70 70 420 5 1 5 1 60 90
Output
3
Note
In the first example you can invite two students with levels 2 and 11. Then you can split the students into two stable groups:
1. [1, 1, 2, 5, 8, 11, 12, 13],
2. [20, 22].
In the second example you are not allowed to invite new students, so you need 3 groups:
1. [1, 1, 5, 5, 20, 20]
2. [60, 70, 70, 70, 80, 90]
3. [420] | instruction | 0 | 22,298 | 14 | 44,596 |
Tags: greedy, sortings
Correct Solution:
```
n,k,x=map(int,input().split())
l=list(map(int,input().split()))
l.sort()
ans=0
l1=[]
for i in range(1,n):
diff=l[i]-l[i-1]
l1.append(diff)
l1.sort()
for diff in l1:
if diff>x:
if x==0:
ans+=1
else:
t=diff//x
if diff/x==diff//x:
t-=1
if k>=t:
k-=t
else:
ans+=1
print(ans+1)
``` | output | 1 | 22,298 | 14 | 44,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, 8, 4, 4] is stable (because 4 - 1 ≤ x, 4 - 4 ≤ x, 8 - 4 ≤ x, 10 - 8 ≤ x), while the group with levels [2, 10, 10, 7] is not stable (7 - 2 = 5 > x).
Apart from the n given students, teachers can invite at most k additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).
For example, if there are two students with levels 1 and 5; x = 2; and k ≥ 1, then you can invite a new student with level 3 and put all the students in one stable group.
Input
The first line contains three integers n, k, x (1 ≤ n ≤ 200 000, 0 ≤ k ≤ 10^{18}, 1 ≤ x ≤ 10^{18}) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}) — the students levels.
Output
In the only line print a single integer: the minimum number of stable groups you can split the students into.
Examples
Input
8 2 3
1 1 5 8 12 13 20 22
Output
2
Input
13 0 37
20 20 80 70 70 70 420 5 1 5 1 60 90
Output
3
Note
In the first example you can invite two students with levels 2 and 11. Then you can split the students into two stable groups:
1. [1, 1, 2, 5, 8, 11, 12, 13],
2. [20, 22].
In the second example you are not allowed to invite new students, so you need 3 groups:
1. [1, 1, 5, 5, 20, 20]
2. [60, 70, 70, 70, 80, 90]
3. [420] | instruction | 0 | 22,299 | 14 | 44,598 |
Tags: greedy, sortings
Correct Solution:
```
import math
import sys
input = sys.stdin.buffer.readline
N, K, X = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
diffs = sorted([A[i + 1] - A[i] for i in range(N - 1)])
ans = 1
for diff in diffs:
if diff > X:
need = (diff - 1) // X
if need <= K:
K -= need
else:
ans += 1
print(ans)
``` | output | 1 | 22,299 | 14 | 44,599 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, 8, 4, 4] is stable (because 4 - 1 ≤ x, 4 - 4 ≤ x, 8 - 4 ≤ x, 10 - 8 ≤ x), while the group with levels [2, 10, 10, 7] is not stable (7 - 2 = 5 > x).
Apart from the n given students, teachers can invite at most k additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).
For example, if there are two students with levels 1 and 5; x = 2; and k ≥ 1, then you can invite a new student with level 3 and put all the students in one stable group.
Input
The first line contains three integers n, k, x (1 ≤ n ≤ 200 000, 0 ≤ k ≤ 10^{18}, 1 ≤ x ≤ 10^{18}) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}) — the students levels.
Output
In the only line print a single integer: the minimum number of stable groups you can split the students into.
Examples
Input
8 2 3
1 1 5 8 12 13 20 22
Output
2
Input
13 0 37
20 20 80 70 70 70 420 5 1 5 1 60 90
Output
3
Note
In the first example you can invite two students with levels 2 and 11. Then you can split the students into two stable groups:
1. [1, 1, 2, 5, 8, 11, 12, 13],
2. [20, 22].
In the second example you are not allowed to invite new students, so you need 3 groups:
1. [1, 1, 5, 5, 20, 20]
2. [60, 70, 70, 70, 80, 90]
3. [420] | instruction | 0 | 22,300 | 14 | 44,600 |
Tags: greedy, sortings
Correct Solution:
```
import io,os,sys,math
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,k,x=map(int,input().split())
l=sorted(map(int,input().split()))
dd=[]
for i in range(n-1):
el1=l[i]
el2=l[i+1]
t=abs(el2-el1)
if t > x:
if t % x == 0:
kkk= t//x -1
else:
kkk = t//x
dd.append(kkk)
dd.sort()
kk=k
c=0
f=True
for i in range(len(dd)):
el=dd[i]
c+=el
if c > kk:
ccc=(len(dd)-1)-i +1
ans=ccc+1
f=False
break
if f:
print(1)
else:
print(ans)
``` | output | 1 | 22,300 | 14 | 44,601 |
Provide tags and a correct Python 3 solution for this coding contest problem.
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
* The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;
* the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;
* and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.
* to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);
* to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
Output
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
Examples
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5 | instruction | 0 | 22,374 | 14 | 44,748 |
Tags: brute force, implementation
Correct Solution:
```
import sys
fin = sys.stdin
n = int(fin.readline())
a = list(map(int, fin.readline().split()))
table = dict()
s = [0] * (n + 1)
for i in range(n):
rec = table.setdefault(a[i], { 'begin' : i, 'end' : i, 'sum' : a[i] })
rec['end'] = i
if a[i] >= 0:
s[i + 1] = s[i] + a[i]
rec['sum'] = s[rec['end'] + 1] - s[rec['begin']]
else:
s[i + 1] += s[i]
rec['sum'] = s[rec['end'] + 1] - s[rec['begin']] + 2 * a[i]
ms = max(v['sum'] for v in table.values() if v['begin'] != v['end'])
for mi in table.keys():
if table[mi]['sum'] == ms:
break
mr = [i + 1 for i in range(n) if i < table[mi]['begin'] or i > table[mi]['end'] or table[mi]['begin'] < i < table[mi]['end'] and a[i] < 0]
print(ms, len(mr))
print(' '.join(map(str, mr)))
``` | output | 1 | 22,374 | 14 | 44,749 |
Provide tags and a correct Python 3 solution for this coding contest problem.
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
* The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;
* the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;
* and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.
* to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);
* to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
Output
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
Examples
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5 | instruction | 0 | 22,375 | 14 | 44,750 |
Tags: brute force, implementation
Correct Solution:
```
from collections import defaultdict
n = int(input())
a = list(map(int,input().split()))
same = defaultdict(list)
only_positive = [max(0,x) for x in a]
partial_sum = [0 for i in range(n+1)]
for i in range(1,n+1):
partial_sum[i] = partial_sum[i-1]+only_positive[i-1]
for i in range(n):
same[a[i]].append(i)
best = -10**18
bl, br = -1, -1
for key in same:
if len(same[key]) >= 2:
l, r = same[key][0], same[key][-1]
cur = key*2 + partial_sum[r]-partial_sum[l+1]
if cur > best:
best = cur
bl, br = l, r
cut = []
for i in range(n):
if not (a[i] >= 0 and bl <= i and i <= br):
if i != bl and i != br:
cut.append(i+1)
print(best,len(cut))
print(*cut)
``` | output | 1 | 22,375 | 14 | 44,751 |
Provide tags and a correct Python 3 solution for this coding contest problem.
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
* The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;
* the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;
* and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.
* to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);
* to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
Output
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
Examples
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5 | instruction | 0 | 22,376 | 14 | 44,752 |
Tags: brute force, implementation
Correct Solution:
```
def main():
n, aa = int(input()), list(map(int, input().split()))
partialsum, s, d = [0] * (n + 1), 0, {}
for i, a in enumerate(aa):
if a > 0:
s += a
partialsum[i] = s
if a in d:
d[a].append(i)
else:
d[a] = [i]
ranges = []
for a, l in d.items():
for i in range(1, len(l)):
hi = l[i]
base = partialsum[hi - 1] + a * 2
for j in range(i):
lo = l[j]
ranges.append((base - partialsum[lo], lo, hi))
s, lo, hi = max(ranges)
res = list(range(1, lo + 1))
for i in range(lo + 1, hi):
if aa[i] < 0:
res.append(i + 1)
res.extend(range(hi + 2, n + 1))
print(s, len(res))
print(" ".join(map(str, res)))
if __name__ == '__main__':
main()
``` | output | 1 | 22,376 | 14 | 44,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
* The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;
* the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;
* and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.
* to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);
* to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
Output
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
Examples
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5 | instruction | 0 | 22,377 | 14 | 44,754 |
Tags: brute force, implementation
Correct Solution:
```
length = int(input())
array = [int(a) for a in input().split()]
maxSum = -10e20
resIndexes = []
for i in range(length):
for j in range(length - 1, -1, -1):
if j > i and array[i] == array[j]:
tmp = sum(array[i:j + 1])
indexes = []
for index in range(i + 1, j):
if array[index] < 0:
tmp -= array[index]
indexes.append(index + 1)
if tmp > maxSum:
maxSum = tmp
indexes += list(range(1, i + 1))
indexes += list(range(j + 2, length + 1))
resIndexes = indexes
print (maxSum, len(resIndexes))
result = [str(a) for a in resIndexes]
print (' '.join(result))
``` | output | 1 | 22,377 | 14 | 44,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
* The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;
* the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;
* and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.
* to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);
* to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
Output
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
Examples
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5 | instruction | 0 | 22,378 | 14 | 44,756 |
Tags: brute force, implementation
Correct Solution:
```
n=int(input())
a=tuple(map(int,input().split()))
c={}
p={}
s=x=y=0
m=-1e18
for i in range(0,len(a)):
d=c.get(a[i])
if d!=None and s-d+a[i]*2>m:
m=s-d+a[i]*2
x,y=p.get(a[i]),i
if(a[i]>0):s+=a[i]
if p.get(a[i])==None:
p[a[i]]=i
c[a[i]]=s
a=[str(i+1) for i in range(0,len(a)) if i!=x and i!=y and (a[i]<0 or i<x or i>y)]
print(m,len(a))
print(" ".join(a))
``` | output | 1 | 22,378 | 14 | 44,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
* The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;
* the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;
* and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.
* to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);
* to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
Output
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
Examples
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5 | instruction | 0 | 22,379 | 14 | 44,758 |
Tags: brute force, implementation
Correct Solution:
```
def main():
n, aa = int(input()), list(map(int, input().split()))
partialsum, s, d, ranges = [0] * n, 0, {}, []
for i, a in enumerate(aa):
if a > 0:
s += a
partialsum[i] = s
if a in d:
d[a].append(i)
else:
d[a] = [i]
ranges = []
for a, l in d.items():
lo, hi = l[0], l[-1]
if lo < hi:
ranges.append((partialsum[hi - 1] - partialsum[lo] + a * 2, lo, hi))
s, lo, hi = max(ranges)
res = list(range(1, lo + 1))
for i in range(lo + 1, hi):
if aa[i] < 0:
res.append(i + 1)
res.extend(range(hi + 2, n + 1))
print(s, len(res))
print(" ".join(map(str, res)))
if __name__ == '__main__':
main()
``` | output | 1 | 22,379 | 14 | 44,759 |
Provide tags and a correct Python 3 solution for this coding contest problem.
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
* The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;
* the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;
* and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.
* to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);
* to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
Output
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
Examples
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5 | instruction | 0 | 22,380 | 14 | 44,760 |
Tags: brute force, implementation
Correct Solution:
```
from sys import stdin
from collections import defaultdict
n = int(stdin.readline().rstrip())
a = [int(x) for x in stdin.readline().rstrip().split(' ')]
mmin = {}
mmax = {}
pref = {} # prefix sums
for i, x in enumerate(a):
if x not in mmin:
mmin[x] = i
mmax[x] = i
if i == 0:
val = max(x, 0)
else:
val = pref[i-1] + max(x, 0)
pref[i] = val
pref[-1] = 0
ks = set(mmin.keys()).intersection(mmax.keys())
fks = [k for k in ks if mmin[k] != mmax[k]]
maxk = None
maxsum = None
for k in fks:
if maxk is None:
maxk = k
maxsum = pref[mmax[k]] - pref[mmin[k]-1]
if k < 0:
maxsum += 2*k
continue
maxcand = pref[mmax[k]] - pref[mmin[k]-1]
if k < 0:
maxcand += 2*k
if maxcand > maxsum:
maxk = k
maxsum = maxcand
cut = 0
cuts = []
for i, val in enumerate(a):
if i < mmin[maxk] or i > mmax[maxk]:
cut += 1
cuts.append(i+1)
continue
if i in [mmin[maxk], mmax[maxk]]:
continue
if val < 0:
cut += 1
cuts.append(i+1)
print(maxsum, cut)
print(' '.join(str(x) for x in cuts))
``` | output | 1 | 22,380 | 14 | 44,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.
Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!
The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:
* The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;
* the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;
* and of course, the walk should be successful: there must be at least two trees in the woodland belt left.
Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
Input
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.
* to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);
* to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
Output
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.
In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.
If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
Examples
Input
5
1 2 3 1 2
Output
8 1
1
Input
5
1 -2 3 1 -2
Output
5 2
2 5 | instruction | 0 | 22,381 | 14 | 44,762 |
Tags: brute force, implementation
Correct Solution:
```
"""
obs1: cu posibila exceptie a capetelor secventei alese,
imi permit sa sterg toate valorile negative din sir
avand in vedere ca am ramas doar cu valori pozitive,
tintesc sa obtin o bucata cat mai lunga de valori
astfel ca atunci cand vreau sa fixez capetele la valorile x -> x
le voi fixa asa: prima aparitie a lui x in sir -> ultima aparitie a lui x in sir
imi fac un vector de sume partiale ale valorilor pozitive
ca sa pot vedea ce am in secventa :)
"""
n = int(input())
v = list(map(int, input().split()))
valmax = max(v) + 100
valmin = min(v) - 100
sol = -(10**18)
first = {}
last = {}
s = [0 for i in range(-2, n+5)]
s[0] = max(v[0], 0)
for i in range(1, len(v)):
s[i] = s[i-1]
if v[i] > 0: s[i] += v[i]
for i in range(0, len(v)):
last[str(v[i])] = i
if not str(v[i]) in first.keys(): first[str(v[i])] = i
left = 0
right = 0
for i in range(0, len(v)):
val = v[i]
if first[str(val)] == last[str(val)]: continue
total = s[ last[str(val)] ] - s[ first[str(val)]-1 ]
if val < 0: total += 2*val
if total > sol:
sol = total
left = first[str(val)]
right = last[str(val)]
cutTrees = []
for i in range(0, left): cutTrees.append(i)
for i in range(left+1, right):
if v[i] < 0: cutTrees.append(i)
for i in range(right+1, n): cutTrees.append(i)
if n == 2: cutTrees = []
print("%i %i" % (sol, len(cutTrees)))
for x in cutTrees: print(x+1, end=' ')
``` | output | 1 | 22,381 | 14 | 44,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.
You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
Input
The first line contains integers n and m (1 ≤ n, m ≤ 105) — the number of team participants and the number of messages. Each of the next m lines contains a message in the format:
* '+ id': the record means that the person with number id (1 ≤ id ≤ n) has logged on to the meeting.
* '- id': the record means that the person with number id (1 ≤ id ≤ n) has logged off from the meeting.
Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.
Output
In the first line print integer k (0 ≤ k ≤ n) — how many people can be leaders. In the next line, print k integers in the increasing order — the numbers of the people who can be leaders.
If the data is such that no member of the team can be a leader, print a single number 0.
Examples
Input
5 4
+ 1
+ 2
- 2
- 1
Output
4
1 3 4 5
Input
3 2
+ 1
- 2
Output
1
3
Input
2 4
+ 1
- 1
+ 2
- 2
Output
0
Input
5 6
+ 1
- 1
- 3
+ 3
+ 4
- 4
Output
3
2 3 5
Input
2 4
+ 1
- 2
+ 2
- 1
Output
0 | instruction | 0 | 22,418 | 14 | 44,836 |
Tags: implementation
Correct Solution:
```
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018
@author: ernesto
'''
n, m = [int(x) for x in input().strip().split(" ")]
posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_mencionados = set()
ultimo_en_salir = [True] * (n + 1)
ultima_salida_inesperada = None
ops = []
if(m > 1):
for _ in range(0, m):
s, n_s = [x for x in input().strip().split(" ")]
n = int(n_s)
ops.append((s, n))
for i in range(0, m):
op, num = ops[i]
cont = False
if op == '+':
cont = not i or (ops[i - 1][0] == '-' and ops[i - 1][1] == num)
posteriores.add(num)
if op == '-':
cont = i == m - 1 or (ops[i + 1][0] == '+' and ops[i + 1][1] == num)
if num not in mencionados:
anteriores.add(num)
ultima_salida_inesperada = num
posteriores.discard(num)
ultimo_en_salir[num] &= not posteriores
continuos[num] &= cont
mencionados.add(num)
# print("anteriores {} posteriores {} continuos {} ops {}".format(anteriores, posteriores, continuos, ops))
if not anteriores and not posteriores:
assert ultima_salida_inesperada is None
if ops[0][0] == '+' and ops[-1][0] == '-' and ops[0][1] == ops[-1][1] and continuos[ops[0][1]] and ultimo_en_salir[ops[0][1]]:
posibles_jefes_mencionados.add(ops[0][1])
else:
if not posteriores:
assert ultima_salida_inesperada is not None
posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores))
assert len(posibles_jefes_filtrados) <= 1
if(posibles_jefes_filtrados):
assert posibles_jefes_filtrados[0] == ops[-1][1]
posibles_jefes_mencionados.add(ops[-1][1])
else:
if not anteriores:
assert ultima_salida_inesperada is None
posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x], posteriores))
# print("posibles {}".format(posibles_jefes_filtrados))
assert len(posibles_jefes_filtrados) <= 1
if(posibles_jefes_filtrados):
assert posibles_jefes_filtrados[0] == ops[0][1]
posibles_jefes_mencionados.add(ops[0][1])
else:
assert ultima_salida_inesperada is not None
# print("continuos {}".format(continuos))
posibles_jefes_mencionados = set(filter(lambda x:ultimo_en_salir[x] and continuos[x] and ultima_salida_inesperada == x, anteriores & posteriores))
# print("posibles jefes menc {}".format(posibles_jefes_mencionados))
posibles_jefes -= (mencionados - posibles_jefes_mencionados)
print(len(posibles_jefes))
if(len(posibles_jefes)):
print(" ".join(map(str, sorted(posibles_jefes))))
``` | output | 1 | 22,418 | 14 | 44,837 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.
You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
Input
The first line contains integers n and m (1 ≤ n, m ≤ 105) — the number of team participants and the number of messages. Each of the next m lines contains a message in the format:
* '+ id': the record means that the person with number id (1 ≤ id ≤ n) has logged on to the meeting.
* '- id': the record means that the person with number id (1 ≤ id ≤ n) has logged off from the meeting.
Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.
Output
In the first line print integer k (0 ≤ k ≤ n) — how many people can be leaders. In the next line, print k integers in the increasing order — the numbers of the people who can be leaders.
If the data is such that no member of the team can be a leader, print a single number 0.
Examples
Input
5 4
+ 1
+ 2
- 2
- 1
Output
4
1 3 4 5
Input
3 2
+ 1
- 2
Output
1
3
Input
2 4
+ 1
- 1
+ 2
- 2
Output
0
Input
5 6
+ 1
- 1
- 3
+ 3
+ 4
- 4
Output
3
2 3 5
Input
2 4
+ 1
- 2
+ 2
- 1
Output
0 | instruction | 0 | 22,419 | 14 | 44,838 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
covers_all = set(range(1, n+1))
in_there = set([])
occurred = set([])
minus_delete_candidates = set([])
plus_delete_candidates = set([])
for i in range(m):
a, b = input().split()
b = int(b)
if a == '+':
in_there.add(b)
covers_all -= (plus_delete_candidates - in_there)
plus_delete_candidates = set([])
if occurred and b not in occurred:
covers_all.discard(b)
else:
if b in in_there:
in_there.remove(b)
else:
covers_all -= minus_delete_candidates
minus_delete_candidates = set([])
if in_there:
covers_all.discard(b)
else:
plus_delete_candidates.add(b)
occurred.add(b)
if b in covers_all:
minus_delete_candidates.add(b)
print(len(covers_all))
if covers_all:
print(' '.join(map(str, sorted(list(covers_all)))))
``` | output | 1 | 22,419 | 14 | 44,839 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.
You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
Input
The first line contains integers n and m (1 ≤ n, m ≤ 105) — the number of team participants and the number of messages. Each of the next m lines contains a message in the format:
* '+ id': the record means that the person with number id (1 ≤ id ≤ n) has logged on to the meeting.
* '- id': the record means that the person with number id (1 ≤ id ≤ n) has logged off from the meeting.
Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.
Output
In the first line print integer k (0 ≤ k ≤ n) — how many people can be leaders. In the next line, print k integers in the increasing order — the numbers of the people who can be leaders.
If the data is such that no member of the team can be a leader, print a single number 0.
Examples
Input
5 4
+ 1
+ 2
- 2
- 1
Output
4
1 3 4 5
Input
3 2
+ 1
- 2
Output
1
3
Input
2 4
+ 1
- 1
+ 2
- 2
Output
0
Input
5 6
+ 1
- 1
- 3
+ 3
+ 4
- 4
Output
3
2 3 5
Input
2 4
+ 1
- 2
+ 2
- 1
Output
0
Submitted Solution:
```
(n, m) = map(int,input().split())
def f(a, b):
if (b <= a):
return a - b
return 1 + b % 2 + f(a, (b + 1) / 2)
print(f(n, m))
``` | instruction | 0 | 22,420 | 14 | 44,840 |
No | output | 1 | 22,420 | 14 | 44,841 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.
You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
Input
The first line contains integers n and m (1 ≤ n, m ≤ 105) — the number of team participants and the number of messages. Each of the next m lines contains a message in the format:
* '+ id': the record means that the person with number id (1 ≤ id ≤ n) has logged on to the meeting.
* '- id': the record means that the person with number id (1 ≤ id ≤ n) has logged off from the meeting.
Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.
Output
In the first line print integer k (0 ≤ k ≤ n) — how many people can be leaders. In the next line, print k integers in the increasing order — the numbers of the people who can be leaders.
If the data is such that no member of the team can be a leader, print a single number 0.
Examples
Input
5 4
+ 1
+ 2
- 2
- 1
Output
4
1 3 4 5
Input
3 2
+ 1
- 2
Output
1
3
Input
2 4
+ 1
- 1
+ 2
- 2
Output
0
Input
5 6
+ 1
- 1
- 3
+ 3
+ 4
- 4
Output
3
2 3 5
Input
2 4
+ 1
- 2
+ 2
- 1
Output
0
Submitted Solution:
```
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018
@author: ernesto
'''
n, m = [int(x) for x in input().strip().split(" ")]
posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_mencionados = set()
ultimo_en_salir = [True] * (n + 1)
ultima_salida_inesperada = None
ops = []
if(m > 1):
for _ in range(0, m):
s, n_s = [x for x in input().strip().split(" ")]
n = int(n_s)
ops.append((s, n))
for i in range(0, m):
op, num = ops[i]
cont = False
if op == '+':
cont = not i or (ops[i - 1][0] == '-' and ops[i - 1][1] == num)
posteriores.add(num)
if op == '-':
cont = i == m - 1 or (ops[i + 1][0] == '+' and ops[i + 1][1] == num)
if num not in mencionados:
anteriores.add(num)
ultima_salida_inesperada = num
posteriores.discard(num)
ultimo_en_salir[num] &= not posteriores
continuos[num] &= cont
mencionados.add(num)
# print("anteriores {} posteriores {} continuos {} ops {}".format(anteriores, posteriores, continuos, ops))
if not anteriores and not posteriores:
assert ultima_salida_inesperada is None
if ops[0][0] == '+' and ops[-1][0] == '-' and ops[0][1] == ops[-1][1] and continuos[ops[0][1]] and ultimo_en_salir[ops[0][1]]:
posibles_jefes_mencionados.add(ops[0][1])
else:
if not posteriores:
assert ultima_salida_inesperada is not None
posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores))
assert len(posibles_jefes_filtrados) == 1
assert posibles_jefes_filtrados[0] == ops[-1][1]
posibles_jefes_mencionados.add(ops[-1][1])
else:
if not anteriores:
assert ultima_salida_inesperada is None
posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x], posteriores))
assert len(posibles_jefes_filtrados) == 1
assert posibles_jefes_filtrados[0] == ops[0][1]
else:
assert ultima_salida_inesperada is not None
posibles_jefes_mencionados = set(filter(lambda x:ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores & posteriores))
# print("posibles jefes menc {}".format(posibles_jefes_mencionados))
posibles_jefes -= (mencionados - posibles_jefes_mencionados)
print(len(posibles_jefes))
if(len(posibles_jefes)):
print(" ".join(map(str, sorted(posibles_jefes))))
``` | instruction | 0 | 22,421 | 14 | 44,842 |
No | output | 1 | 22,421 | 14 | 44,843 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.
You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
Input
The first line contains integers n and m (1 ≤ n, m ≤ 105) — the number of team participants and the number of messages. Each of the next m lines contains a message in the format:
* '+ id': the record means that the person with number id (1 ≤ id ≤ n) has logged on to the meeting.
* '- id': the record means that the person with number id (1 ≤ id ≤ n) has logged off from the meeting.
Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.
Output
In the first line print integer k (0 ≤ k ≤ n) — how many people can be leaders. In the next line, print k integers in the increasing order — the numbers of the people who can be leaders.
If the data is such that no member of the team can be a leader, print a single number 0.
Examples
Input
5 4
+ 1
+ 2
- 2
- 1
Output
4
1 3 4 5
Input
3 2
+ 1
- 2
Output
1
3
Input
2 4
+ 1
- 1
+ 2
- 2
Output
0
Input
5 6
+ 1
- 1
- 3
+ 3
+ 4
- 4
Output
3
2 3 5
Input
2 4
+ 1
- 2
+ 2
- 1
Output
0
Submitted Solution:
```
n,m = input().split()
n=int(n)
m=int(m)
q=[]
notl=[]
for i in range(m):
s = input()
l = s.split(" ")
l[1] = int(l[1])
q.append((l[0],l[1]))
for i in range(m):
if q[i][0] == '-':
if i!=0:
if q[i-1][0] =='-':
notl.append(q[i-1][1])
elif q[i-1][0] == '+' and q[i-1][1] != q[i][1]:
notl.append(q[i-1][1])
notl.append(q[i][1])
if i!=m-1:
if q[i+1][0] == '-':
notl.append(q[i][1])
elif q[i+1][0] == '+' and q[i+1][1] != q[i][1]:
notl.append(q[i+1][1])
notl.append(q[i][1])
else:
if i!=0:
if q[i-1][0] == '-' and q[i-1][1] != q[i][1]:
notl.append(q[i-1][1])
notl.append(q[i][1])
elif q[i-1][0] == '+':
notl.append(q[i][1])
if i!=m-1:
if q[i+1][0] == '-' and q[i+1][1] != q[i][1]:
notl.append(q[i+1][1])
notl.append(q[i][1])
elif q[i+1][0] == '+':
notl.append(q[i+1][1])
ans1 = set(notl)
ans = set(list(range(1,n+1)))
ans2 = list(ans - ans1)
print(len(ans2))
if len(ans2)>0:
for i in range(len(ans2)):
print(ans2[i], end = " ")
``` | instruction | 0 | 22,422 | 14 | 44,844 |
No | output | 1 | 22,422 | 14 | 44,845 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.
You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
Input
The first line contains integers n and m (1 ≤ n, m ≤ 105) — the number of team participants and the number of messages. Each of the next m lines contains a message in the format:
* '+ id': the record means that the person with number id (1 ≤ id ≤ n) has logged on to the meeting.
* '- id': the record means that the person with number id (1 ≤ id ≤ n) has logged off from the meeting.
Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.
Output
In the first line print integer k (0 ≤ k ≤ n) — how many people can be leaders. In the next line, print k integers in the increasing order — the numbers of the people who can be leaders.
If the data is such that no member of the team can be a leader, print a single number 0.
Examples
Input
5 4
+ 1
+ 2
- 2
- 1
Output
4
1 3 4 5
Input
3 2
+ 1
- 2
Output
1
3
Input
2 4
+ 1
- 1
+ 2
- 2
Output
0
Input
5 6
+ 1
- 1
- 3
+ 3
+ 4
- 4
Output
3
2 3 5
Input
2 4
+ 1
- 2
+ 2
- 1
Output
0
Submitted Solution:
```
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018
@author: ernesto
'''
n, m = [int(x) for x in input().strip().split(" ")]
posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_mencionados = set()
ultimo_en_salir = [True] * (n + 1)
ultima_salida_inesperada = None
ops = []
if(m > 1):
for _ in range(0, m):
s, n_s = [x for x in input().strip().split(" ")]
n = int(n_s)
ops.append((s, n))
for i in range(0, m):
op, num = ops[i]
cont = False
if op == '+':
cont = not i or (ops[i - 1][0] == '-' and ops[i - 1][1] == num)
posteriores.add(num)
if op == '-':
cont = i == m - 1 or (ops[i + 1][0] == '+' and ops[i + 1][1] == num)
if num not in mencionados:
anteriores.add(num)
ultima_salida_inesperada = num
posteriores.discard(num)
ultimo_en_salir[num] &= not posteriores
continuos[num] &= cont
mencionados.add(num)
# print("anteriores {} posteriores {} continuos {} ops {}".format(anteriores, posteriores, continuos, ops))
if not anteriores and not posteriores:
assert ultima_salida_inesperada is None
if ops[0][0] == '+' and ops[-1][0] == '-' and ops[0][1] == ops[-1][1] and continuos[ops[0][1]] and ultimo_en_salir[ops[0][1]]:
posibles_jefes_mencionados.add(ops[0][1])
else:
if not posteriores:
assert ultima_salida_inesperada is not None
posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores))
assert len(posibles_jefes_filtrados) <= 1
if(posibles_jefes_filtrados):
assert posibles_jefes_filtrados[0] == ops[-1][1]
posibles_jefes_mencionados.add(ops[-1][1])
else:
if not anteriores:
assert ultima_salida_inesperada is None
posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x], posteriores))
# print("posibles {}".format(posibles_jefes_filtrados))
assert len(posibles_jefes_filtrados) <= 1
if(posibles_jefes_filtrados):
assert posibles_jefes_filtrados[0] == ops[0][1]
posibles_jefes_mencionados.add(ops[0][1])
else:
assert ultima_salida_inesperada is not None
posibles_jefes_mencionados = set(filter(lambda x:ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores & posteriores))
# print("posibles jefes menc {}".format(posibles_jefes_mencionados))
posibles_jefes -= (mencionados - posibles_jefes_mencionados)
print(len(posibles_jefes))
if(len(posibles_jefes)):
print(" ".join(map(str, sorted(posibles_jefes))))
``` | instruction | 0 | 22,423 | 14 | 44,846 |
No | output | 1 | 22,423 | 14 | 44,847 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.
Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.
<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.
Tokitsukaze wants to know the number of operations she would do in total.
Input
The first line contains three integers n, m and k (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5, 1 ≤ m, k ≤ n) — the number of items, the number of special items to be discarded and the number of positions in each page.
The second line contains m distinct integers p_1, p_2, …, p_m (1 ≤ p_1 < p_2 < … < p_m ≤ n) — the indices of special items which should be discarded.
Output
Print a single integer — the number of operations that Tokitsukaze would do in total.
Examples
Input
10 4 5
3 5 7 10
Output
3
Input
13 4 5
7 8 9 10
Output
1
Note
For the first example:
* In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
* In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
* In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.
For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once. | instruction | 0 | 22,912 | 14 | 45,824 |
Tags: implementation, two pointers
Correct Solution:
```
if __name__ == '__main__':
n,m,k = map(int, input().split())
l = list(map(int, input().split()))
i = 0
operations = 0
while i < m:
j = i
cu = (l[i]-1-j)//k
while i < m and (l[i]-1-j)//k == cu:
i+=1
operations+=1
print(operations)
``` | output | 1 | 22,912 | 14 | 45,825 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.
Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.
<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.
Tokitsukaze wants to know the number of operations she would do in total.
Input
The first line contains three integers n, m and k (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5, 1 ≤ m, k ≤ n) — the number of items, the number of special items to be discarded and the number of positions in each page.
The second line contains m distinct integers p_1, p_2, …, p_m (1 ≤ p_1 < p_2 < … < p_m ≤ n) — the indices of special items which should be discarded.
Output
Print a single integer — the number of operations that Tokitsukaze would do in total.
Examples
Input
10 4 5
3 5 7 10
Output
3
Input
13 4 5
7 8 9 10
Output
1
Note
For the first example:
* In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
* In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
* In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.
For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once. | instruction | 0 | 22,913 | 14 | 45,826 |
Tags: implementation, two pointers
Correct Solution:
```
n, m, k = map(int, input().split(' '))
p = tuple(map(int, input().split(' ')))
d = 0
part = (p[0]-1) // k
moves = 0
skip = 0
for pi in p:
if (pi-1-d) // k == part:
skip += 1
continue
d += skip
part = (pi-1-d) // k
skip = 1
moves += 1
print(moves+1)
``` | output | 1 | 22,913 | 14 | 45,827 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.
Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.
<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.
Tokitsukaze wants to know the number of operations she would do in total.
Input
The first line contains three integers n, m and k (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5, 1 ≤ m, k ≤ n) — the number of items, the number of special items to be discarded and the number of positions in each page.
The second line contains m distinct integers p_1, p_2, …, p_m (1 ≤ p_1 < p_2 < … < p_m ≤ n) — the indices of special items which should be discarded.
Output
Print a single integer — the number of operations that Tokitsukaze would do in total.
Examples
Input
10 4 5
3 5 7 10
Output
3
Input
13 4 5
7 8 9 10
Output
1
Note
For the first example:
* In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
* In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
* In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.
For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once. | instruction | 0 | 22,914 | 14 | 45,828 |
Tags: implementation, two pointers
Correct Solution:
```
n,m,k=map(int,input().split())
p=list(map(int,input().split()))
count=0
delete=0
now=0
while now<m:
up=((p[now]-delete-1)//k+1)*k+delete
while now<m and p[now]<=up:
now+=1
delete+=1
count+=1
print(count)
``` | output | 1 | 22,914 | 14 | 45,829 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.
Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.
<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.
Tokitsukaze wants to know the number of operations she would do in total.
Input
The first line contains three integers n, m and k (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5, 1 ≤ m, k ≤ n) — the number of items, the number of special items to be discarded and the number of positions in each page.
The second line contains m distinct integers p_1, p_2, …, p_m (1 ≤ p_1 < p_2 < … < p_m ≤ n) — the indices of special items which should be discarded.
Output
Print a single integer — the number of operations that Tokitsukaze would do in total.
Examples
Input
10 4 5
3 5 7 10
Output
3
Input
13 4 5
7 8 9 10
Output
1
Note
For the first example:
* In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
* In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
* In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.
For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once. | instruction | 0 | 22,915 | 14 | 45,830 |
Tags: implementation, two pointers
Correct Solution:
```
n,m,k = map(int,input().split())
a = list(map(int,input().split()))
ans,result = 0,0
page,new_result = None,1
for i in range(m):
if (a[i]-result)//k!=page:
ans+=1
result = new_result
page = (a[i]-result)//k
new_result+=1
print(ans)
``` | output | 1 | 22,915 | 14 | 45,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.
Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.
<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.
Tokitsukaze wants to know the number of operations she would do in total.
Input
The first line contains three integers n, m and k (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5, 1 ≤ m, k ≤ n) — the number of items, the number of special items to be discarded and the number of positions in each page.
The second line contains m distinct integers p_1, p_2, …, p_m (1 ≤ p_1 < p_2 < … < p_m ≤ n) — the indices of special items which should be discarded.
Output
Print a single integer — the number of operations that Tokitsukaze would do in total.
Examples
Input
10 4 5
3 5 7 10
Output
3
Input
13 4 5
7 8 9 10
Output
1
Note
For the first example:
* In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
* In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
* In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.
For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once. | instruction | 0 | 22,916 | 14 | 45,832 |
Tags: implementation, two pointers
Correct Solution:
```
n, m, k = map(int, input().split())
p = list(map(int, input().split()))
c = 0
tmp = 0
ops = 0
curr_page = (p[0] - 1) // k
for pp in p:
if curr_page != (pp - 1 - c) // k:
c += tmp
tmp = 1
ops += 1
curr_page = (pp - 1 - c) // k
else:
tmp += 1
print(ops + 1)
``` | output | 1 | 22,916 | 14 | 45,833 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.
Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.
<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.
Tokitsukaze wants to know the number of operations she would do in total.
Input
The first line contains three integers n, m and k (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5, 1 ≤ m, k ≤ n) — the number of items, the number of special items to be discarded and the number of positions in each page.
The second line contains m distinct integers p_1, p_2, …, p_m (1 ≤ p_1 < p_2 < … < p_m ≤ n) — the indices of special items which should be discarded.
Output
Print a single integer — the number of operations that Tokitsukaze would do in total.
Examples
Input
10 4 5
3 5 7 10
Output
3
Input
13 4 5
7 8 9 10
Output
1
Note
For the first example:
* In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
* In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
* In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.
For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once. | instruction | 0 | 22,917 | 14 | 45,834 |
Tags: implementation, two pointers
Correct Solution:
```
from collections import deque
n,m,k=map(int,input().split())
p=deque(int(x) - 1 for x in input().split())
numRemoved = 0
ops = 0
while len(p) > 0:
currRemoved = 1
front = p.popleft()
currPage = (front - numRemoved)//k
#print(str(ops) + ": " + str(front))
while (len(p) > 0 and (p[0] - numRemoved)//k == currPage):
currRemoved += 1
p.popleft()
ops += 1
numRemoved += currRemoved
print(ops)
``` | output | 1 | 22,917 | 14 | 45,835 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.
Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.
<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.
Tokitsukaze wants to know the number of operations she would do in total.
Input
The first line contains three integers n, m and k (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5, 1 ≤ m, k ≤ n) — the number of items, the number of special items to be discarded and the number of positions in each page.
The second line contains m distinct integers p_1, p_2, …, p_m (1 ≤ p_1 < p_2 < … < p_m ≤ n) — the indices of special items which should be discarded.
Output
Print a single integer — the number of operations that Tokitsukaze would do in total.
Examples
Input
10 4 5
3 5 7 10
Output
3
Input
13 4 5
7 8 9 10
Output
1
Note
For the first example:
* In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
* In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
* In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.
For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once. | instruction | 0 | 22,918 | 14 | 45,836 |
Tags: implementation, two pointers
Correct Solution:
```
from collections import defaultdict
import sys
input = sys.stdin.readline
inf = 100000000000000000 # 1e17
mod = 998244353
n, m, k = map(int, input().split())
A = [0] + list(map(int, input().split()))
sum = 0
ans = 0
now = 1
while now <= m:
r = sum
r += (A[now] - sum - 1) // k * k
r += k
while now <= m and r >= A[now]:
sum += 1
now += 1
ans += 1
print(ans)
# the end
``` | output | 1 | 22,918 | 14 | 45,837 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.