message stringlengths 2 30.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 237 109k | cluster float64 10 10 | __index_level_0__ int64 474 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17. | instruction | 0 | 32,580 | 10 | 65,160 |
Tags: dp, greedy, sortings
Correct Solution:
```
n,m,k=map(int,input().split())
arr=list(map(int,input().split()))
offer=[list(map(int,input().split())) for _ in range(m)]
arr=sorted(arr)
arr=arr[:k]
arr=arr[::-1]
acum=[0]
for i in range(k):
acum.append(acum[-1]+arr[i])
dp=[acum[i] for i in range(k+1)]
for x,y in offer:
if x>k:
continue
for i in range(x,k+1):
dp[i]=min(dp[i],dp[i-x]+(acum[i]-acum[i-x])-(acum[i]-acum[i-y]))
tmp=dp[0]
for i in range(1,k+1):
tmp=min(tmp,dp[i-1])+arr[i-1]
dp[i]=min(dp[i],tmp)
for x,y in offer:
if x>k:
continue
for i in range(x,k+1):
dp[i]=min(dp[i],dp[i-x]+(acum[i]-acum[i-x])-(acum[i]-acum[i-y]))
tmp=dp[0]
for i in range(1,k+1):
tmp=min(tmp,dp[i-1])+arr[i-1]
dp[i]=min(dp[i],tmp)
print(dp[k])
``` | output | 1 | 32,580 | 10 | 65,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17. | instruction | 0 | 32,581 | 10 | 65,162 |
Tags: dp, greedy, sortings
Correct Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Codeforces Round #552 (Div. 3)
Problem F. Shovels Shop
:author: Kitchen Tong
:mail: kctong529@gmail.com
Please feel free to contact me if you have any question
regarding the implementation below.
"""
__version__ = '2.0'
__date__ = '2019-04-17'
import sys
from heapq import heappush, heappop
def buy_shovels(k, shovels, discounts):
if 1 not in discounts:
discounts[1] = 0
accums = [0]
for s in shovels:
accums.append(s + accums[-1])
for i in range(k):
for x, y in discounts.items():
if i + x > k:
continue
perhaps = accums[i] + sum(shovels[i+y:i+x])
accums[i+x] = min(accums[i+x], perhaps)
return accums[-1]
def main(argv=None):
n, m, k = map(int, input().split())
costs = list(map(int, input().split()))
discounts = dict()
for line in range(m):
x, y = map(int, input().split())
if x > k:
# this discount is useless as we can't buy more than k
continue
if x not in discounts:
discounts[x] = y
else:
discounts[x] = max(discounts[x], y)
print(buy_shovels(k, sorted(costs)[:k], discounts))
return 0
if __name__ == "__main__":
STATUS = main()
sys.exit(STATUS)
``` | output | 1 | 32,581 | 10 | 65,163 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17. | instruction | 0 | 32,582 | 10 | 65,164 |
Tags: dp, greedy, sortings
Correct Solution:
```
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
a = sorted(a)
a = a[:k]
d = [(1, 0)]
for i in range(m):
x, y = map(int, input().split())
if x > k:
continue
d.append((x, y))
d = sorted(d)
s = [0] * (k + 1)
s[1] = a[0]
for i in range(1, k + 1):
s[i] = s[i - 1] + a[i - 1]
INF = float('inf')
dp = [INF] * (k + 1)
dp[0] = 0
for i in range(k + 1):
for j in range(len(d)):
x, y = d[j]
if i + x <= k:
dp[i + x] = min(dp[i + x], dp[i] + s[i + x] - s[i + y])
else:
break
print(dp[k])
``` | output | 1 | 32,582 | 10 | 65,165 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17. | instruction | 0 | 32,583 | 10 | 65,166 |
Tags: dp, greedy, sortings
Correct Solution:
```
from audioop import reverse
n, m, k = map(int,input().split())
price = list(map(int,input().split()))
offer = [0] * (k + 1)
for i in range(m):
x , y = map(int,input().split())
if x <= k:
offer[x] = max(offer[x] , y)
price.sort()
for _ in range(n-k):
price.pop()
price.sort(reverse=True)
prep = [0] * (k + 1)
for i in range(k):
prep[i + 1] = prep[i] + price[i]
min_price = [prep[k]] * (k + 1)
min_price[0] = 0
for i in range(k):
min_price[i + 1] = min(min_price[i + 1],min_price[i] + price[i])
for j in range(1 , k + 1):
if offer[j] == 0:
continue
if i + j > k:
break
min_price[i + j] = min(min_price[i + j] , min_price[i] + prep[i + j - offer[j]] -prep[i])
print(min_price[k])
``` | output | 1 | 32,583 | 10 | 65,167 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17. | instruction | 0 | 32,584 | 10 | 65,168 |
Tags: dp, greedy, sortings
Correct Solution:
```
# http://codeforces.com/contest/1154/problem/F
# Explain: https://codeforces.com/blog/entry/66586?locale=en
from collections import defaultdict
def input2int():
return map(int, input().split())
n, m, k = input2int()
cost = list(input2int())
cost = sorted(cost)[:k]
# cost.reverse()
# print(cost)
preSum = defaultdict(int)
for i in range(k):
preSum[i] = preSum[i - 1] + cost[i]
preSum[k] = preSum[k - 1]
# print(preSum)
offer = []
for i in range(m):
x, y = input2int()
if x <= k:
offer.append((x, y))
# print(offer)
dp = defaultdict(lambda: int(1e9))
dp[0] = 0
for i in range(k + 1):
if i < k:
dp[i + 1] = min(dp[i] + cost[i], dp[i + 1])
for _ in offer:
x, y = _
# print("i: {}, x: {}, y: {}".format(i, x, y))
if i + x > k:
continue
# print('sum: {}'.format(preSum[i + x] - preSum[i + y]))
dp[i + x] = min(dp[i + x], dp[i] + preSum[i + x - 1] - preSum[i + y - 1])
# print(dp)
# print(dp)
print(dp[k])
``` | output | 1 | 32,584 | 10 | 65,169 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17. | instruction | 0 | 32,585 | 10 | 65,170 |
Tags: dp, greedy, sortings
Correct Solution:
```
n,m,k = map(int,input().split())
ai = list(map(int,input().split()))
ar = [0] * k
for i in range(m):
x,y = list(map(int,input().split()))
x -= 1
if x < k:
ar[x] = max(ar[x],y)
ai.sort()
big = 10**9
ar2 = [big] * (k+1)
ar3 = [0] * (k+1)
ar3[0] = 0
for i in range(1,k+1):
ar3[i] = ar3[i-1] + ai[i-1]
ar2[k] = 0
for i in range(k,0,-1):
for j in range(i):
ar2[i-j-1] = min(ar2[i-j-1],ar2[i] + ar3[i] - ar3[i - (j + 1 - ar[j])])
print(ar2[0])
``` | output | 1 | 32,585 | 10 | 65,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
Submitted Solution:
```
from sys import stdin
import math
from copy import deepcopy
from collections import defaultdict
def process_offer(offers):
aux = []
for i in offers:
temp = offers[i]
temp.sort()
aux.append([i, temp[-1]])
aux = sorted(aux, key = lambda x: x[0])
return aux
def make(first, second):
return str(first) + ' ' + str(second)
def brute(arr, dp, offers, index, remain):
#print(index, remain)
# base case:
if remain == 0:
return 0
if make(index, remain) in dp:
return dp[make(index, remain)]
min_cost = arr[index] + brute(arr, dp, offers, index + 1, remain - 1)
#print(min_cost)
for i in range(len(offers)):
cost = 0
if offers[i][0] <= remain:
free = offers[i][1]
for j in range(index + free, index + offers[i][0]):
cost += arr[j]
cost += brute(arr, dp, offers, index + offers[i][0], remain - offers[i][0])
min_cost = min(min_cost, cost)
else:
break
dp[make(index, remain)] = min_cost
return min_cost
n, m, k = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
arr.sort()
offers = defaultdict(list)
for _ in range(m):
x, y = list(map(int, stdin.readline().split()))
offers[x].append(y)
offers = process_offer(offers)
dp = dict()
print(brute(arr, dp, offers, 0, k))
``` | instruction | 0 | 32,586 | 10 | 65,172 |
Yes | output | 1 | 32,586 | 10 | 65,173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
b = [0]
for i in range(k - 1, -1, -1):
b.append(a[i])
c = [0] * (k + 1)
for i in range(1, k + 1):
c[i] += b[i] + c[i - 1]
s = [0] * (k + 1)
for _ in range(m):
x, y = map(int, input().split())
if x <= k:
s[x] = max(s[x], y)
inf = 1145141919810
dp = [0] * (k + 1)
for i in range(1, k + 1):
dpi = inf
for j in range(1, i + 1):
d = i - j + 1
dpi = min(dpi, dp[j - 1] - c[j - 1] + c[i - s[d]])
dp[i] = dpi
ans = dp[k]
print(ans)
``` | instruction | 0 | 32,587 | 10 | 65,174 |
Yes | output | 1 | 32,587 | 10 | 65,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
Submitted Solution:
```
#Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue
#sys.stdin = open("input.txt", "r")
MOD = 10**9+7
n, m, k = map(int, input().split())
a = sorted(map(int, input().split()))
a = a[:k]
ps = [0]
for i in range(k):
ps.append(ps[-1]+a[i])
bf = []
temp = [0 for i in range(k+1)]
for i in range(m):
b, f = map(int, input().split())
if b <= k:
temp[b] = max(temp[b], f)
for i in range(1, k+1):
if temp[i] != 0:
bf.append((i, temp[i]))
bf = [(1, 0)] + sorted(bf, key = lambda x: (x[0]-x[1], b))
dp = [[-1 for i in range(len(bf))] for i in range(k+1)]
for i in range(len(bf)): dp[0][i] = 0
for i in range(1, k+1): dp[i][0] = ps[i]
for i in range(1, k+1):
for j in range(1, len(bf)):
dp[i][j] = dp[i][j-1]
b = bf[j][0]
f = bf[j][1]
if b <= i:
dp[i][j] = min(dp[i][j], dp[i-b][len(bf)-1]+ps[i]-ps[i-b+f])
print(dp[k][len(bf)-1])
``` | instruction | 0 | 32,588 | 10 | 65,176 |
Yes | output | 1 | 32,588 | 10 | 65,177 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
Submitted Solution:
```
'''input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
'''
from sys import stdin
import math
from copy import deepcopy
from collections import defaultdict
def process_offer(offers):
aux = []
for i in offers:
temp = offers[i]
temp.sort()
aux.append([i, temp[-1]])
aux = sorted(aux, key = lambda x: x[0])
return aux
def make(first, second):
return str(first) + ' ' + str(second)
def brute(arr, dp, offers, index, remain):
#print(index, remain)
# base case:
if remain == 0:
return 0
if make(index, remain) in dp:
return dp[make(index, remain)]
min_cost = arr[index] + brute(arr, dp, offers, index + 1, remain - 1)
#print(min_cost)
for i in range(len(offers)):
cost = 0
if offers[i][0] <= remain:
free = offers[i][1]
for j in range(index + free, index + offers[i][0]):
cost += arr[j]
cost += brute(arr, dp, offers, index + offers[i][0], remain - offers[i][0])
min_cost = min(min_cost, cost)
else:
break
dp[make(index, remain)] = min_cost
return min_cost
# main starts
n, m, k = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
arr.sort()
offers = defaultdict(list)
for _ in range(m):
x, y = list(map(int, stdin.readline().split()))
offers[x].append(y)
offers = process_offer(offers)
dp = dict()
print(brute(arr, dp, offers, 0, k))
#print(dp)
``` | instruction | 0 | 32,589 | 10 | 65,178 |
Yes | output | 1 | 32,589 | 10 | 65,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Codeforces Round #552 (Div. 3)
Problem F. Shovels Shop
:author: Kitchen Tong
:mail: kctong529@gmail.com
Please feel free to contact me if you have any question
regarding the implementation below.
"""
__version__ = '0.1'
__date__ = '2019-04-16'
import sys
def buy_shovels(k, shovels, discounts):
answer = 0
total = sum(shovels)
best_discount = 0
for x, y in discounts.items():
if best_discount == total:
return 0
if x == y:
discount = sum(shovels[(k % x):])
if discount > best_discount:
best_discount = discount
answer = (x, y)
continue
discount = 0
num_of_discounts = k // x
for n in range(num_of_discounts):
for s in range(k % x + n * x,
k % x + n * x + y):
discount += shovels[s]
if discount > best_discount:
best_discount = discount
answer = (x, y)
if k == 2000:
print(answer, shovels[:748])
return total - best_discount
def main(argv=None):
n, m, k = map(int, input().split())
costs = list(map(int, input().split()))
discounts = dict()
for line in range(m):
x, y = map(int, input().split())
if x > k:
# this discount is useless as we can't buy more than k
continue
if x not in discounts:
discounts[x] = y
else:
discounts[x] = max(discounts[x], y)
print(buy_shovels(k, sorted(costs)[:k], discounts))
return 0
if __name__ == "__main__":
STATUS = main()
sys.exit(STATUS)
``` | instruction | 0 | 32,590 | 10 | 65,180 |
No | output | 1 | 32,590 | 10 | 65,181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Codeforces Round #552 (Div. 3)
Problem F. Shovels Shop
:author: Kitchen Tong
:mail: kctong529@gmail.com
Please feel free to contact me if you have any question
regarding the implementation below.
"""
__version__ = '0.1'
__date__ = '2019-04-16'
import sys
def buy_shovels(k, shovels, discounts):
if k == 2000:
print(discounts)
total = sum(shovels)
best_discount = 0
for x, y in discounts.items():
if best_discount == total:
return 0
if x == y:
discount = sum(shovels[(k % x):])
if discount > best_discount:
best_discount = discount
continue
discount = 0
num_of_discounts = k // x
for n in range(num_of_discounts):
for s in range(k % x + n * x,
k % x + n * x + y):
discount += shovels[s]
if discount > best_discount:
best_discount = discount
return total - best_discount
def main(argv=None):
n, m, k = map(int, input().split())
costs = list(map(int, input().split()))
discounts = dict()
for line in range(m):
x, y = map(int, input().split())
if x > k:
# this discount is useless as we can't buy more than k
continue
if x not in discounts:
discounts[x] = y
else:
discounts[x] = max(discounts[x], y)
print(buy_shovels(k, sorted(costs)[:k], discounts))
return 0
if __name__ == "__main__":
STATUS = main()
sys.exit(STATUS)
``` | instruction | 0 | 32,591 | 10 | 65,182 |
No | output | 1 | 32,591 | 10 | 65,183 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
Submitted Solution:
```
# http://codeforces.com/contest/1154/problem/F
# Explain: https://codeforces.com/blog/entry/66586?locale=en
from collections import defaultdict
def input2int():
return map(int, input().split())
n, m, k = input2int()
cost = list(input2int())
cost = sorted(cost)[:k]
# cost.reverse()
# print(cost)
preSum = defaultdict(int)
for i in range(k):
preSum[i] = preSum[i - 1] + cost[i]
preSum[k] = preSum[k - 1]
# print(preSum)
offer = []
for i in range(m):
x, y = input2int()
if x <=k:
offer.append((x, y))
# print(offer)
dp = defaultdict(lambda: int(1e9))
dp[0] = 0
for i in range(k + 1):
for _ in offer:
x, y = _
# print("i: {}, x: {}, y: {}".format(i, x, y))
if i < k:
dp[i + 1] = min(dp[i] + cost[i], dp[i + 1])
if i + x > k:
continue
# print('sum: {}'.format(preSum[i + x] - preSum[i + y]))
dp[i + x] = min(dp[i + x], dp[i] + preSum[i + x-1] - preSum[i + y-1])
# print(dp)
# print(dp)
print(dp[k])
``` | instruction | 0 | 32,592 | 10 | 65,184 |
No | output | 1 | 32,592 | 10 | 65,185 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
Submitted Solution:
```
def main():
global visited, adj, sets
print = out.append
''' Cook your dish here! '''
n, m, k = get_list()
li = get_list()
li.sort()
offers = [[10**10, 0]] # Prevent index out of bound in while loop at line 15
for _ in range(m):
offers.append(get_list())
offers.sort()
best_y = [0]
ptr = -1
for i in range(k):
best_y.append(best_y[-1])
while offers[ptr+1][0] <= i+1:
ptr += 1
best_y[-1] = max(best_y[-1], offers[ptr][1])
x, y = 1, i
while x<=y:
best_y[-1] = max(best_y[-1], best_y[x]+best_y[y])
x+=1
y-=1
#print(best_y, li)
dp = [0]
for i in range(1, k+1):
prefix_sm = [0]
dp.append(dp[-1]+li[i-1])
#print(i, dp)
for j in range(i-1, 0, -1):
prefix_sm.append(prefix_sm[-1]+li[j])
x = i-j
#print("Prefix sm", prefix_sm, x)
dp[-1] = min(dp[-1], dp[j]+ prefix_sm[x-best_y[x]])
print(dp[k])
''' Coded with love at India by Satyam Kumar '''
import sys
#from collections import defaultdict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda: int(input())
get_list = lambda: list(map(int, input().split()))
main()
# [main() for _ in range(int(input()))]
print(*out, sep='\n')
``` | instruction | 0 | 32,593 | 10 | 65,186 |
No | output | 1 | 32,593 | 10 | 65,187 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | instruction | 0 | 33,052 | 10 | 66,104 |
Tags: dsu, implementation, sortings, two pointers
Correct Solution:
```
n = int(input())
input_ = list(map(int, input().split(' ')))
pos = n
a = [0 for i in range(n+1)]
res = 1
ans = [1]
for x in input_:
a[x] = 1
res += 1
while a[pos]==1:
pos -= 1
res -= 1
ans.append(res)
print (' '.join(map(str, ans)))
``` | output | 1 | 33,052 | 10 | 66,105 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | instruction | 0 | 33,053 | 10 | 66,106 |
Tags: dsu, implementation, sortings, two pointers
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
p = [0] * (n + 1)
ans = [1] * (n + 1)
ind = n
for i in range(n):
p[a[i] - 1] = 1
while ind > 0 and p[ind - 1] == 1:
ind -= 1
ans[i + 1] = 1 + (i + 1) - (n - ind)
print(' '.join(map(str, ans)))
``` | output | 1 | 33,053 | 10 | 66,107 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | instruction | 0 | 33,054 | 10 | 66,108 |
Tags: dsu, implementation, sortings, two pointers
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split()))
ar2 = [False] * (n+2)
ar2[-1] = True
res = [1]
acc = 1
ptr = n
for e in arr:
ar2[e] = True
acc += 1
while ar2[ptr]:
ptr -= 1
res.append(acc - (n-ptr))
print(*res)
``` | output | 1 | 33,054 | 10 | 66,109 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | instruction | 0 | 33,055 | 10 | 66,110 |
Tags: dsu, implementation, sortings, two pointers
Correct Solution:
```
n = int(input())
positions = [int(x) for x in input().split(" ")]
output = '1 '
pointer_to_right_wall = n - 1
coins = [False for i in range(len(positions))]
filled = 1
for i in range(len(positions)):
coins[positions[i] - 1] = True
if positions[i]-1 == pointer_to_right_wall:
count = 0
while coins[pointer_to_right_wall] == True:
if pointer_to_right_wall == 0 and coins[0] == True:
count += 1
break
pointer_to_right_wall -= 1
count += 1
filled = filled - count + 1
else:
filled += 1
output += str(filled) + ' '
print(output[:-1])
``` | output | 1 | 33,055 | 10 | 66,111 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | instruction | 0 | 33,056 | 10 | 66,112 |
Tags: dsu, implementation, sortings, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import defaultdict
n = int(input())
ans = [0 for _ in range(n + 1)]
ans[0] = 1
ans[-1] = 1
sample = [0 for _ in range(n)]
last = n - 1
q = list(map(int, input().split()))
for i in range(n - 1):
x = q[i]
sample[x-1] = 1
if x - 1 == last:
while sample[x-1] != 0:
x -= 1
last = x - 1
target = n - i - 2
#print(last, target)
ans[i + 1] = last - target + 1
print(*ans)
``` | output | 1 | 33,056 | 10 | 66,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | instruction | 0 | 33,057 | 10 | 66,114 |
Tags: dsu, implementation, sortings, two pointers
Correct Solution:
```
n = int(input())
l = list(map(int,input().split()))
print(1,end = " ")
ptr = n-1
v = [0]*n
for i in range(n):
v[l[i]-1] = 1
while(ptr>=0 and v[ptr]==1):ptr-=1
print(i+1-(n-1-ptr)+1,end = " ")
``` | output | 1 | 33,057 | 10 | 66,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | instruction | 0 | 33,058 | 10 | 66,116 |
Tags: dsu, implementation, sortings, two pointers
Correct Solution:
```
n = int(input())
x = [0]*n
a = 0
p = list(map(int, input().split()))
z = n-1
ans = ['1']
for i in range(n):
x[p[i]-1] = 1
a += 1
while z> -1 and x[z] == 1:
z-=1
a-=1
ans.append(str(a+1))
print(' '.join(ans))
``` | output | 1 | 33,058 | 10 | 66,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | instruction | 0 | 33,059 | 10 | 66,118 |
Tags: dsu, implementation, sortings, two pointers
Correct Solution:
```
n = int(input())
input_ = list(map(int, input().split()))
pos = n
a = [0 for i in range(n+1)]
res = 1
ans = [1]
for x in input_:
a[x] = 1
res += 1
while a[pos]==1:
pos -= 1
res -= 1
ans.append(res)
print(' '.join(map(str, ans)))
``` | output | 1 | 33,059 | 10 | 66,119 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Submitted Solution:
```
from sys import stdin, stdout
n = int(stdin.readline())
values = list(map(int, stdin.readline().split()))
used = [0 for i in range(n)]
right, cnt = n, 0
ans = 1
stdout.write(str(ans) + ' ')
for v in values:
used[v - 1] = 1
ans += 1
while right and used[right - 1]:
ans -= 1
right -= 1
stdout.write(str(ans) + ' ')
``` | instruction | 0 | 33,060 | 10 | 66,120 |
Yes | output | 1 | 33,060 | 10 | 66,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Submitted Solution:
```
n = int(input())
p = list(map(int, input().split()))
lp = n+1
ans = [1]
vis = [0 for i in range(n)]
ans = [1]
top = n
hardness = 1
for i in range(len(p)):
vis[p[i]-1] = 1
hardness += 1
while vis[top-1] == 1 and top > 0:
top -= 1
hardness -=1
ans.append(hardness)
print(' '.join([str(i) for i in ans]))
``` | instruction | 0 | 33,061 | 10 | 66,122 |
Yes | output | 1 | 33,061 | 10 | 66,123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Submitted Solution:
```
'''
basiccallu jistne conse pairs
'''
def f(n,a):
a=list(map(lambda s:s-1,a))
ar=[0]*(n+1)
l=0
ans=[1]
hi=(n-1)
cnt=0
for i in a:
if i==hi:
ar[i]=1
hi-=1
# print(hi)
while ar[hi]==1:
hi-=1
cnt-=1
else:
ar[i]=1
cnt+=1
ans.append(cnt+1)
return ans
a=int(input())
ls=list(map(int,input().strip().split()))
print(*f(a,ls))
``` | instruction | 0 | 33,062 | 10 | 66,124 |
Yes | output | 1 | 33,062 | 10 | 66,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
p = list(map(int, input().split()))
flag = [1]*n
r = n-1
cnt = 0
print(1, end=' ')
for i in range(n-1):
flag[p[i]-1] = 0
while flag[r]==0:
r -= 1
cnt += 1
print(i+2-cnt, end=' ')
print(1)
``` | instruction | 0 | 33,063 | 10 | 66,126 |
Yes | output | 1 | 33,063 | 10 | 66,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
Submitted Solution:
```
n = int(input())
input_ = list(map(int, input().split()))
pos = n
a = [0 for i in range(n+1)]
res = 1
ans = [1]
print(1, end=" ")
for x in input_:
a[x] = 1
res += 1
while a[pos]==1:
pos -= 1
res -= 1
ans.append(res)
print(' '.join(map(str, ans)))
``` | instruction | 0 | 33,064 | 10 | 66,128 |
No | output | 1 | 33,064 | 10 | 66,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. | instruction | 0 | 33,565 | 10 | 67,130 |
Tags: data structures, greedy, implementation
Correct Solution:
```
import sys,bisect
input = sys.stdin.readline
n = int(input())
sell = []
pos = [-1 for i in range(n)]
rest_left = [i-1 for i in range(2*n)]
rest_right = [i+1 for i in range(2*n)]
for i in range(2*n):
s = input().split()
if s[0]=="+":
continue
else:
sell.append(i)
pos[int(s[1])-1] = len(sell) - 1
left = [i-1 for i in range(n)]
right = [i+1 for i in range(n)]
res = [-1 for i in range(2*n)]
for i in range(n):
R = sell[pos[i]]
if left[pos[i]]!=-1:
L = sell[left[pos[i]]]
else:
L = -1
sold = rest_left[R]
#print(L,R,sold)
if L<sold:
res[sold] = i + 1
if rest_right[sold]<2*n:
rest_left[rest_right[sold]] = rest_left[sold]
if rest_left[sold]!=-1:
rest_right[rest_left[sold]] = rest_right[sold]
if rest_right[R]<2*n:
rest_left[rest_right[R]] = rest_left[R]
if rest_left[sold]!=-1:
rest_right[rest_left[R]] = rest_right[R]
if right[pos[i]]<n:
left[right[pos[i]]] = left[pos[i]]
if left[pos[i]]!=-1:
right[left[pos[i]]] = right[pos[i]]
else:
exit(print("NO"))
#print(rest_left)
#print(rest_right)
#print(res)
ans = []
for a in res:
if a!=-1:
ans.append(a)
print("YES")
print(*ans)
``` | output | 1 | 33,565 | 10 | 67,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. | instruction | 0 | 33,566 | 10 | 67,132 |
Tags: data structures, greedy, implementation
Correct Solution:
```
"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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")
import collections as col
import math, string
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
MOD = 10**9+7
"""
"""
def solve():
N = getInt()
A = []
flag = True
tmp = []
res = []
ops = []
for i in range(2*N):
ops.append(getStr())
ops.reverse()
for i in range(2*N):
curr = ops[i]
if curr[0] == '-':
num = int(curr[2:])
if not tmp or tmp[-1] > num:
tmp.append(num)
else:
print("NO")
return
elif tmp:
res.append(tmp.pop())
else:
print("NO")
return
print("YES")
res = res[::-1]
print(*res)
return
#for _ in range(getInt()):
solve()
``` | output | 1 | 33,566 | 10 | 67,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. | instruction | 0 | 33,567 | 10 | 67,134 |
Tags: data structures, greedy, implementation
Correct Solution:
```
import sys
import heapq
input = sys.stdin.readline
n = int(input())
data = [[x for x in input().split()] for _ in range(2 * n)]
q = []
result = []
for i in data[::-1]:
if i[0] == "-":
heapq.heappush(q, int(i[1]))
else:
if q:
m = heapq.heappop(q)
result.append(m)
else:
print("NO")
sys.exit()
result = result[::-1]
q = []
current = 0
for i in data:
if i[0] == "-":
m = heapq.heappop(q)
if m != int(i[1]):
print("NO")
sys.exit()
else:
heapq.heappush(q, result[current])
current += 1
print("YES")
print(*result)
``` | output | 1 | 33,567 | 10 | 67,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. | instruction | 0 | 33,568 | 10 | 67,136 |
Tags: data structures, greedy, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
import heapq
n = int(input())
tmp = [list(input().split()) for i in range(2 * n)]
info = [-1] * (2 * n)
for i, q in enumerate(tmp):
if q[0] == "-":
val = int(q[1])
info[i] = val
hq = []
p = [-1] * (2 * n)
i = 2 * n
for val in info[::-1]:
i -= 1
if val != -1:
heapq.heappush(hq, val)
else:
if not hq:
print("NO")
exit()
val = heapq.heappop(hq)
p[i] = val
hq = []
res = []
for i in range(2 * n):
if p[i] != -1:
heapq.heappush(hq, p[i])
res.append(p[i])
else:
val = heapq.heappop(hq)
if val != info[i]:
print("NO")
exit()
print("YES")
print(" ".join(map(str, res)))
``` | output | 1 | 33,568 | 10 | 67,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. | instruction | 0 | 33,569 | 10 | 67,138 |
Tags: data structures, greedy, implementation
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
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=-10**6, func=lambda a, b: max(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)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(50001)]
pp=[]
def SieveOfEratosthenes(n=50000):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
for i in range(50001):
if prime[i]:
pp.append(i)
#---------------------------------running code------------------------------------------
import heapq
data = []
for i in range(2 * int(input())):
data.append(input().split())
avalible = []
result = []
try:
for i in data[::-1]:
if i[0] == "-":
heapq.heappush(avalible, int(i[1]))
else:
m = heapq.heappop(avalible)
result.append(m)
result = result[::-1]
avalible = []
p = 0
for i in data:
if i[0] == "-":
m = heapq.heappop(avalible)
if m != int(i[1]):
print("NO")
sys.exit()
else:
heapq.heappush(avalible, result[p])
p += 1
except Exception:
print("NO")
sys.exit()
print("YES")
print(*result)
``` | output | 1 | 33,569 | 10 | 67,139 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. | instruction | 0 | 33,570 | 10 | 67,140 |
Tags: data structures, greedy, implementation
Correct Solution:
```
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.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(io.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()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#endregion
from heapq import heappush, heappop
n = int(input())
ops = [input() for _ in range(n + n)]
queue = []
ans = []
for i in range(2*n - 1, -1, -1):
if ops[i][0] == '+':
if not queue:
print('NO')
exit(0)
ans.append(heappop(queue))
else:
val = int(ops[i].split()[1])
if queue and val > queue[0]:
print('NO')
exit(0)
heappush(queue, val)
print('YES')
print(' '.join(str(x) for x in reversed(ans)))
``` | output | 1 | 33,570 | 10 | 67,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. | instruction | 0 | 33,571 | 10 | 67,142 |
Tags: data structures, greedy, implementation
Correct Solution:
```
import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
# 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")
stdin, stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
mod = pow(10, 9) + 7
mod2 = 998244353
def inp(): return stdin.readline().strip()
def iinp(): return int(inp())
def out(var, end="\n"): stdout.write(str(var)+"\n")
def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end)
def lmp(): return list(mp())
def mp(): return map(int, inp().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)]
def ceil(a, b): return (a+b-1)//b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def isprime(x):
if x<=1: return False
if x in (2, 3): return True
if x%2 == 0: return False
for i in range(3, int(sqrt(x))+1, 2):
if x%i == 0: return False
return True
n = iinp()
seq = []
for i in range(2*n):
x = inp().split()
if len(x)==1:
seq.append(x[0])
else:
seq.append(int(x[1]))
hp = []
flg = True
ansl = []
for x in seq[::-1]:
if x == '+':
if not hp:
flg = False
break
ansl.append(heappop(hp))
else:
if hp:
tmp = heappop(hp)
if tmp < x:
flg = False
break
heappush(hp, tmp)
heappush(hp, x)
if flg:
out("YES\n"+' '.join(map(str, ansl[::-1])))
else:
out("NO")
``` | output | 1 | 33,571 | 10 | 67,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. | instruction | 0 | 33,572 | 10 | 67,144 |
Tags: data structures, greedy, implementation
Correct Solution:
```
import heapq
import sys
import os
import sys
from io import BytesIO, IOBase
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")
n=int(input())
res=[]
for i in range(2*n):
res.append(list(map(str,input().split())))
ans=[]
ord=[]
res.reverse()
for j in res:
if j[0]=="-":
heapq.heappush(ord,int(j[1]))
else:
if ord!=[]:
ans.append(heapq.heappop(ord))
ans.reverse()
res.reverse()
val=[]
i=0
for j in res:
if j[0]=="+":
heapq.heappush(val,ans[i])
i+=1
else:
if val!=[]:
p=heapq.heappop(val)
if p!=int(j[1]):
print('NO')
sys.exit()
else:
print('NO')
sys.exit()
print("YES")
print(*ans)
``` | output | 1 | 33,572 | 10 | 67,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there.
Submitted Solution:
```
import sys
import heapq
input = sys.stdin.readline
def main():
N = int(input())
S = [[x for x in input().split()] for _ in range(2 * N)]
q = []
ans = []
for s in S[::-1]:
if s[0] == "-":
heapq.heappush(q, int(s[1]))
else:
if q:
c = heapq.heappop(q)
ans.append(c)
else:
print("NO")
return
ans2 = ans[::-1]
q = []
current = 0
for s in S:
if s[0] == "-":
c = heapq.heappop(q)
if c != int(s[1]):
print("NO")
return
else:
heapq.heappush(q, ans2[current])
current += 1
print("YES")
print(*ans2)
if __name__ == '__main__':
main()
``` | instruction | 0 | 33,573 | 10 | 67,146 |
Yes | output | 1 | 33,573 | 10 | 67,147 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there.
Submitted Solution:
```
from bisect import bisect_right, bisect_left
import sys
input = sys.stdin.readline
def main():
n = int(input())
pm = 0
lst = []
for _ in range(2 * n):
s = input().strip().split()
if s[0] == "+":
pm += 1
lst.append(-1)
else:
pm -= 1
lst.append(int(s[1]))
if pm < 0:
print("NO")
return
ans = []
que = []
for i in lst[::-1]:
if i == -1:
ans.append(que.pop())
else:
if que and que[-1] < i:
print("NO")
return
que.append(i)
print("YES")
print(*ans[::-1])
main()
``` | instruction | 0 | 33,574 | 10 | 67,148 |
Yes | output | 1 | 33,574 | 10 | 67,149 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there.
Submitted Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
import heapq
def main():
n=int(input())
a=[input() for x in range(2*n)]
a.reverse()
pq=[]
chk=0
ans=[]
temp=[]
for x in a:
#print(pq)
if x=='+':
if len(pq)==0:
chk=1
break
else:
topop=heapq.heappop(pq)
ans.append(topop)
else:
heapq.heappush(pq,int(x.split(" ")[1]))
if chk==1:
print("NO")
else:
ans.reverse()
temp=[]
cnt=0
a.reverse()
for x in a:
if x=='+':
heapq.heappush(temp,ans[cnt])
cnt+=1
else:
if heapq.heappop(temp)!=int(x.split(" ")[1]):
print("NO")
return 0
print("YES")
print(*ans)
#-----------------------------BOSS-------------------------------------!
# 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")
# endregion
if __name__ == "__main__":
main()
``` | instruction | 0 | 33,575 | 10 | 67,150 |
Yes | output | 1 | 33,575 | 10 | 67,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
events=[]
for i in range(2*n):
x=input()
if x=="+\n":
events.append([0])
else:
x,y=x.split()
events.append([1,int(y)])
poss=True
shelf=[]
placed=[]
while len(events)>0:
ev=events.pop()
if ev[0]==0:
if len(shelf)==0:
poss=False
break
x=shelf.pop()
placed.append(x)
else:
x=ev[1]
if len(shelf)>0 and shelf[-1]<x:
poss=False
break
shelf.append(x)
if poss:
cpl=[0]*n
for i in range(n):
cpl[i]=placed[-i-1]
print("YES")
print(*cpl)
else:
print("NO")
``` | instruction | 0 | 33,576 | 10 | 67,152 |
Yes | output | 1 | 33,576 | 10 | 67,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there.
Submitted Solution:
```
import heapq
from sys import exit
n = int(input())
heap = []
queries = []
for _ in range(2 * n):
queries.append(input())
queries.reverse()
the_order_of_the_shuriken = []
for query in queries:
if query[0] == '-':
if heap and heap[0] < int(query[2]):
exit(print('NO'))
heapq.heappush(heap, int(query[2]))
else:
if not heap:
exit(print('NO'))
the_order_of_the_shuriken.append(heapq.heappop(heap))
the_order_of_the_shuriken.reverse()
print('YES')
print(*the_order_of_the_shuriken)
``` | instruction | 0 | 33,577 | 10 | 67,154 |
No | output | 1 | 33,577 | 10 | 67,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there.
Submitted Solution:
```
import heapq
import sys
input = sys.stdin.readline
for _ in range(1):
n = int(input())
ans = [0]*n
cnt = 0
flag = 1
ind = -1
mi = []
# heapq.heapify(mi)
for i in range(2*n):
l = list(map(str,input().split()))
if len(l) == 1:
ind += 1
cnt += 1
else:
x = int(l[-1])
val = n-cnt+1
if val > n:
flag = 0
if val >= x:
if ans[ind] != 0:
mi.append(x)
else:
ans[ind] = x
cnt -= 1
else:
flag = 0
if flag:
mi = mi[::-1]
for i in range(n):
if ans[i] == 0:
ans[i] = mi.pop()
print("YES")
print(*ans)
else:
print("NO")
``` | instruction | 0 | 33,578 | 10 | 67,156 |
No | output | 1 | 33,578 | 10 | 67,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there.
Submitted Solution:
```
a = int(input())
isRight = True
#1 wave Counting
plusov = 0
minusov = 0
counter = 0
last = " "
suriks = [-1] * a
def setFirst(wt):
for j in range(a):
if suriks[j] == -1:
suriks[j] = wt
return
vitrina_now = 0
for i in range(2 * a):
s = input()
if s[0] == '+':
plusov += 1
vitrina_now += 1
counter+=1
else: #-
vitrina_now -= 1
if vitrina_now < 0:
isRight = False
minusov += 1
#suriks += (s[2]) + " "
if last[0] == '-':
if int(last[2]) > int(s[2]):
isRight = False
setFirst(s[2])
elif last[0] == '+':
suriks[counter-1] = s[2]
#for i in suriks:
# print(i, end=' ')
#print()
last = s
if plusov != a or minusov != a:
isRight = False
if isRight:
print("YES")
for i in suriks:
print(i, end=' ')
else:
print("NO")
``` | instruction | 0 | 33,579 | 10 | 67,158 |
No | output | 1 | 33,579 | 10 | 67,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.
Tenten keeps a record for all events, and she ends up with a list of the following types of records:
* + means that she placed another shuriken on the showcase;
* - x means that the shuriken of price x was bought.
Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
Input
The first line contains the only integer n (1β€ nβ€ 10^5) standing for the number of shurikens.
The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type.
Output
If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO".
In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.
Examples
Input
4
+
+
- 2
+
- 3
+
- 1
- 4
Output
YES
4 2 3 1
Input
1
- 1
+
Output
NO
Input
3
+
+
+
- 2
- 1
- 3
Output
NO
Note
In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid.
In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.
In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there.
Submitted Solution:
```
def solve():
n = int(input())
inp = [input() for i in range(2*n)]
if inp[0] != '+':
return 'NO'
nums = sorted(list(map(lambda f: int(f.split()[1]), list(filter(lambda x: x != '+', inp)))))
add = 0
sold = 0
x = [0] * (n+1)
ans = []
tmp = []
prev = None
for i in nums:
x[i] = i
try:
for i in inp:
if i == '+':
if sold == 0:
add += 1
continue
elif add >= sold:
minv = None
for l in range(len(tmp)):
if minv == None or minv > tmp[l]:
minv = tmp[l]
if x[tmp[l]] != 0:
ans.append(tmp[l])
x[tmp[l]] = 0
else:
del tmp[l]
add -= len(tmp)
if minv != None:
for k in range(minv, len(x)):
if add == 0:
break
elif x[k] != 0:
add -= 1
ans.append(x[k])
x[k] = 0
tmp = []
add = 1
sold = 0
prev = None
else:
sold += 1
sell = int(i.split()[1])
if prev == None:
prev = sell
elif prev > sell:
return 'NO'
else:
prev = sell
tmp.append(sell)
except Exception as e:
print(e)
if add > 0:
for i in tmp:
if add == 0:
break
else:
add -= 1
ans.append(i)
anss = ' '.join(map(str, ans))
return f'YES\n{anss}'
print(solve())
``` | instruction | 0 | 33,580 | 10 | 67,160 |
No | output | 1 | 33,580 | 10 | 67,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.
Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
Submitted Solution:
```
#dsu
from sys import stdin, stdout
cin = stdin.readline
cout = stdout.write
'''
def bfs(x):
visited[x] = 1
qu = [x]
while len(qu) > 0:
for a in v[qu[0]]:
if visited[a]:
continue
visited[a] = 1
qu.append(a)
qu.pop(0)
'''
def find(x):
#print('find ', x)
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(x, y):
xset = find(x)
yset = find(y)
if xset == yset:
return
if rank[xset] > rank[yset]:
#parent[yset] = xset
t = xset
xset = yset
yset = t
parent[xset] = yset
#print(1000, xset, yset)
rank[yset] += rank[xset]
#s.add(yset)
n, m = map(int, cin().split())
#v = [set() for _ in range(m+1)]
ans = 0
count = 0
#s = set()
rank = [1] * (m+1)
parent = [i for i in range(m+1)]
visited = [0] * (m+1)
for i in range(n):
a = list(map(int, cin().split()))
if a[0] == 0:
ans += 1
continue
visited[a[1]] = 1
for i in range(2, a[0]+1):
#v[i].add(a[1])
#v[a[1]].add(i)
union(a[i], a[1])
visited[a[i]] = 1
#print(v)
#visited = [0] * (m+1)
'''
for i in range(1, m+1):
if not v[i] or visited[i]:
continue
bfs(i)
count += 1
'''
#nos = 0
for i in range(1, m+1):
if visited[i] and find(i) == i:
count += 1
#print(count)
#print(s)
#print(parent)
cout(str(ans+max(0, count-1)))
``` | instruction | 0 | 33,670 | 10 | 67,340 |
Yes | output | 1 | 33,670 | 10 | 67,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.
Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
Submitted Solution:
```
rd = lambda: list(map(int, input().split()))
def root(x):
if f[x]!=x: f[x] = root(f[x])
return f[x]
n, m = rd()
N=range(n)
f=list(N)
lang = [0]*n
for i in N:
lang[i] = set(rd()[1:])
for i in N:
for j in N[:i]:
if j==root(j) and lang[j].intersection(lang[i]):
f[j] = i
lang[i] = lang[i].union(lang[j])
print(sum(1 for i in N if i==root(i)) - (sum(map(len, lang))>0))
``` | instruction | 0 | 33,671 | 10 | 67,342 |
Yes | output | 1 | 33,671 | 10 | 67,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.
Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
Submitted Solution:
```
from sys import stdin, stdout
illiterate = 0
def find(node):
if dsu[node] == node:
return node
else:
dsu[node] = find(dsu[node])
return dsu[node]
n, m = map(int, stdin.readline().strip().split())
dsu = [ i for i in range(n+1)]
language = [0]*(m+1)
for j in range(n):
arr = list(map(int, stdin.readline().strip().split()))
if arr[0] != 0:
for i in arr[1:]:
if not language[i]:
language[i] = find(j+1)
else:
dsu[find(language[i])] = find(j+1)
else:
illiterate += 1
count = 0
for i in range(1, n+1):
if i == dsu[i]:
count += 1
if count == illiterate:
print(n)
else:
print(count-1)
``` | instruction | 0 | 33,672 | 10 | 67,344 |
Yes | output | 1 | 33,672 | 10 | 67,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.
Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
Submitted Solution:
```
m,n=map(int,input().strip().split())
arr=[]
v=0
for k in range(m):
list1=list(map(int,input().strip().split()))
list1=list1[1:]
if list1==[]:
v+=1
else:
arr.append(set(list1))
i=0
while i<len(arr):
flag=True
for j in arr[i+1:]:
if arr[i]&j:
arr[i]|=j
arr.remove(j)
flag=False
break
if flag:
i+=1
if len(arr)==0:
print(v)
else:
print(v+len(arr)-1)
``` | instruction | 0 | 33,673 | 10 | 67,346 |
Yes | output | 1 | 33,673 | 10 | 67,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.
Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
Submitted Solution:
```
n, m = map(int, input().split())
l = []
cnt0 = 0
for i in range(n):
t = [int(x) for x in input().split()]
if t.pop(0) == 0:
cnt0 += 1
l.append(t)
lan = [-1]*(m+1)
for i in range(n):
new = set()
pos = []
for y in l[i]:
if lan[y] != -1:
new.add(lan[y])
if len(new) == 0:
for y in l[i]:
lan[y] = i
else:
temp = new.pop()
for y in l[i]:
lan[y] = temp
for i in range(m):
if lan[i] in new:
lan[i] = temp
new = set()
for i in range(1, m+1):
if not lan[i] in new and lan[i]!=-1:
new.add(lan[i])
ans = 0
lenn = len(new)
if lenn != 0:
ans += lenn - 1
if cnt0 != 0:
ans += cnt0
else:
ans += n
print(ans)
``` | instruction | 0 | 33,674 | 10 | 67,348 |
No | output | 1 | 33,674 | 10 | 67,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.
Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
Submitted Solution:
```
n,m=map(int,input().strip().split())
arr=[]
v=0
for k in range(m):
list1=list(map(int,input().strip().split()))
list1=list1[1:]
if list1==[]:
v+=1
else:
arr.append(set(list1))
i=0
while i<len(arr):
flag=True
for j in arr[i+1:]:
if arr[i]&j:
arr[i]|=j
arr.remove(j)
flag=False
break
if flag:
i+=1
if len(arr)==0:
print(v)
else:
print(v+len(arr)-1)
``` | instruction | 0 | 33,675 | 10 | 67,350 |
No | output | 1 | 33,675 | 10 | 67,351 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 β€ n, m β€ 100) β the number of employees and the number of languages.
Then n lines follow β each employee's language list. At the beginning of the i-th line is integer ki (0 β€ ki β€ m) β the number of languages the i-th employee knows. Next, the i-th line contains ki integers β aij (1 β€ aij β€ m) β the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
Submitted Solution:
```
def contains(lst, grph):
for el in lst:
if len(el & grph) > 0: return True
return False
res = 0
n, m = map(int, input().split(' '))
graphs = []
for _ in range(n):
line = input().split(' ')[1:]
if len(line) == 0:
res += 1
continue
flag = False
for lang in line:
for graph in graphs:
if int(lang) in graph:
flag = True
graph |= (set(map(int, line)))
if not flag:
graphs.append(set(map(int, line)))
print(graphs)
new_graphs = []
for graph in graphs:
flag = False
for group in new_graphs:
if contains(group, graph):
flag = True
group.append(graph)
break
if not flag:
new_graphs.append([graph])
print(len(new_graphs)-1+res)
``` | instruction | 0 | 33,676 | 10 | 67,352 |
No | output | 1 | 33,676 | 10 | 67,353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.