message stringlengths 2 48.6k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 318 108k | cluster float64 8 8 | __index_level_0__ int64 636 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. | instruction | 0 | 48,954 | 8 | 97,908 |
Tags: data structures, dp, greedy
Correct Solution:
```
from collections import deque
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
q = deque([])
ans = [0] * n
tmp_ans = 0
for i in range(n):
ind = i
l_ind = i
while True:
if not q:
q.append((a[i], l_ind))
tmp_ans += a[i] * (l_ind + 1)
break
if q[-1][0] <= a[i]:
tmp_ans += a[i] * (l_ind - q[-1][1])
q.append((a[i], l_ind))
break
else:
height, l = q.pop()
if not q:
tmp_ans -= height * (l + 1)
else:
tmp_ans -= height * (l - q[-1][1])
ind = l
ans[i] = tmp_ans
b = a[::-1]
q = deque([])
ans2 = [0] * n
tmp_ans = 0
for i in range(n):
ind = i
l_ind = i
while True:
if not q:
q.append((b[i], l_ind))
tmp_ans += b[i] * (l_ind + 1)
break
if q[-1][0] <= b[i]:
tmp_ans += b[i] * (l_ind - q[-1][1])
q.append((b[i], l_ind))
break
else:
height, l = q.pop()
if not q:
tmp_ans -= height * (l + 1)
else:
tmp_ans -= height * (l - q[-1][1])
ind = l
ans2[i] = tmp_ans
max_ans = 0
ind = -1
for i in range(n):
tmp = ans[i] + ans2[n - 1 - i] - a[i]
if max_ans < tmp:
max_ans = tmp
ind = i
i = ind
ans = [0] * n
tmp = a[i]
l = i
r = i
max_height = a[i]
ans[i] = a[i]
for j in range(0, l)[::-1]:
if a[j] >= max_height:
tmp += max_height
else:
tmp += a[j]
max_height = a[j]
ans[j] = max_height
max_height = a[i]
for j in range(r + 1, n):
if a[j] >= max_height:
tmp += max_height
else:
tmp += a[j]
max_height = a[j]
ans[j] = max_height
print(*ans)
``` | output | 1 | 48,954 | 8 | 97,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. | instruction | 0 | 48,955 | 8 | 97,910 |
Tags: data structures, dp, greedy
Correct Solution:
```
def main():
import sys
input = sys.stdin.buffer.readline
N = int(input())
A = list(map(int, input().split()))
inc = [0] * N
st = [(0, 1)]
S = 0
for i, a in enumerate(A):
if a > st[-1][0]:
S += a
inc[i] = S
st.append((a, 1))
else:
cnt = 1
while a < st[-1][0]:
b, num = st.pop()
S -= b * num
cnt += num
S += cnt * a
inc[i] = S
st.append((a, cnt))
dec = [0] * N
st = [(0, 1)]
S = 0
for i, a in enumerate(reversed(A)):
if a > st[-1][0]:
S += a
dec[i] = S
st.append((a, 1))
else:
cnt = 1
while a < st[-1][0]:
b, num = st.pop()
S -= b * num
cnt += num
S += cnt * a
dec[i] = S
st.append((a, cnt))
dec.reverse()
best = -1
mid = -1
for i in range(N - 1):
if inc[i] + dec[i + 1] > best:
mid = i
best = inc[i] + dec[i + 1]
ans = [0] * N
ans[mid] = A[mid]
prev = A[mid]
for j in range(mid - 1, -1, -1):
ans[j] = min(prev, A[j])
prev = ans[j]
mid += 1
prev = A[mid]
for j in range(mid, N):
ans[j] = min(prev, A[j])
prev = ans[j]
print(*ans)
if __name__ == '__main__':
main()
``` | output | 1 | 48,955 | 8 | 97,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. | instruction | 0 | 48,956 | 8 | 97,912 |
Tags: data structures, dp, greedy
Correct Solution:
```
import collections
n = int(input())
m = [int(num) for num in input().split()]
rightlessque = collections.deque([])
indrightless = [n]*n
for i in range(n):
while rightlessque and m[i]<m[rightlessque[0]]:
indrightless[rightlessque.popleft()] = i
rightlessque.appendleft(i)
leftlessque = collections.deque([])
indleftless = [-1]*n
for i in range(n-1,-1,-1):
while leftlessque and m[i]<m[leftlessque[0]]:
indleftless[leftlessque.popleft()] = i
leftlessque.appendleft(i)
leftval = [0]*n
for i in range(n):
if(indleftless[i]==-1):
leftval[i]= (i+1)*m[i]
else:
leftval[i] = leftval[indleftless[i]] + m[i]*(i - indleftless[i])
rightval = [0]*n
for i in range(n-1,-1,-1):
if(indrightless[i]==n):
rightval[i] = (n-i)*m[i]
else:
rightval[i] = rightval[indrightless[i]] + m[i]*(indrightless[i]-i)
maxx = 0
ind = 0
for i in range(n):
num = (leftval[i]+rightval[i]-m[i])
if(num>maxx):
maxx = num
ind = i
finalans = [0]*n
i = ind
while(i>=0):
curr = i
while(curr>indleftless[i]):
finalans[curr]=m[i]
curr-=1
i = indleftless[i]
i = ind
while(i<n):
curr = i
while(curr<indrightless[i]):
finalans[curr]=m[i]
curr+=1
i = indrightless[i]
for i in finalans:
print(i,end = " ")
print()
``` | output | 1 | 48,956 | 8 | 97,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. | instruction | 0 | 48,957 | 8 | 97,914 |
Tags: data structures, dp, greedy
Correct Solution:
```
import heapq
n=int(input())
M=[int(i) for i in input().split()]
def f(X):
H=[]
Ret=[0]*n
tot=0
for i,x in enumerate(X):
haba=0
while H:
h=-heapq.heappop(H)
t,y=h//(10**6),h%(10**6)
if t<=x:
heapq.heappush(H,-(t*(10**6)+y))
break
else:
tot-=(t-x)*y
haba+=y
heapq.heappush(H,-(x*(10**6)+haba+1))
Ret[i]=tot+x
tot+=x
return Ret
A1,A2=f(M),f(M[::-1])[::-1]
A=[A1[i]+A2[i]-M[i] for i in range(n)]
Ans=[0]*n
ma=max(A)
for i in range(n):
if A[i]==ma:
m=i
Ans[m]=M[m]
for i in reversed(range(m)):
Ans[i]=min(Ans[i+1],M[i])
for i in range(m+1,n):
Ans[i]=min(Ans[i-1],M[i])
print(*Ans)
``` | output | 1 | 48,957 | 8 | 97,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. | instruction | 0 | 48,958 | 8 | 97,916 |
Tags: data structures, dp, greedy
Correct Solution:
```
import operator
from sys import stdin
n = int(input())
floors = [int(x) for x in stdin.readline().split()]
left = [0]*n
right = [0]*n
def left_index(lst):
# algorithm to find the nearest element to the left that is smaller
# empty stack
m = len(lst)
S = []
index_list = []
for i in range(m):
while S != []:
if lst[S[-1]] > lst[i]:
S.pop()
else:
index_list.append(S[-1])
break
if S == []:
index_list.append(i)
S.append(i)
return index_list
# calculating sum of left and right separately, supposing pos t is the peak of the scrapers
'''
def left_right(flrs, lst):
c_max = floors[0]
c_min = floors[0]
last = 0
for i in range(n):
if flrs[i] <= c_min:
lst[i] = flrs[i]*(i + 1)
print (lst)
elif c_min < flrs[i] < c_max:
# find left/right most index which is less than or equal to flrs[i]
for j in range(i - 1, -1, -1):
if flrs[j] <= flrs[i]:
break
lst[i] = lst[j] + (i - j)*flrs[i]
print(lst)
else:
if floors[i - 1] >= floors[i]:
lst[i] = -1
else:
lst[i] = lst[i - 1] + floors[i]
print(lst)
if floors[i] > c_max:
c_max = floors[i]
elif floors[i] < c_min:
c_min = floors[i]
def left_right(flrs, lst):
c_max = flrs[0]
c_min = flrs[0]
lst[0] = flrs[0]
for i in range(1, n):
if flrs[i] >= flrs[i - 1]:
lst[i] = lst[i - 1] + flrs[i]
else:
s = 0
m = flrs[i]
for j in range(i, -1, -1):
s += min(m, flrs[j])
if flrs[j] < m:
m = flrs[j]
lst[i] = s
'''
def left_right(flrs, lst):
li = left_index(flrs)
for i in range(n):
# in this case, it is the minimum
if i == li[i]:
lst[i] = flrs[i]*(i + 1)
else:
lst[i] = lst[li[i]] + (i - li[i])*flrs[i]
left_right(floors, left)
left_right(floors[::-1], right)
right = right[::-1]
c_max = 0
ind = 0
for i in range(n):
if left[i] != -1 and right[i] != -1:
if left[i] + right[i] - floors[i] > c_max:
c_max = left[i] + right[i] - floors[i]
ind = i
#creating the list
to_print = [0]*n
to_print[ind] = floors[ind]
m = floors[ind]
for i in range(ind - 1, -1, -1):
to_print[i] = min(floors[i], m)
if floors[i] < m:
m = floors[i]
m = floors[ind]
for i in range(ind + 1, n):
to_print[i] = min(floors[i], m)
if floors[i] < m:
m = floors[i]
# printing the created list
for i in to_print:
print(int(i), end=" ")
``` | output | 1 | 48,958 | 8 | 97,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. | instruction | 0 | 48,959 | 8 | 97,918 |
Tags: data structures, dp, greedy
Correct Solution:
```
n = int(input())
sp = list(map(int, input().split()))
forw = [0 for i in range(n)]
backw = [0 for i in range(n)]
stack = [(0, -1, 0)]
for i in range(n):
while (sp[i] <= stack[-1][0]):
stack.pop()
stack.append((sp[i], i, (i - stack[-1][1]) * sp[i] + stack[-1][2]))
forw[i] = stack[-1][2]
revsp = sp[::-1]
stack = [(0, -1, 0)]
for i in range(n):
while (revsp[i] <= stack[-1][0]):
stack.pop()
stack.append((revsp[i], i, (i - stack[-1][1]) * revsp[i] + stack[-1][2]))
backw[i] = stack[-1][2]
backw = backw[::-1]
#print(forw)
#print(backw)
center = 0
ans_center = 0
for i in range(n):
if ans_center < backw[i] + forw[i] - sp[i]:
center = i
ans_center = backw[i] + forw[i] - sp[i]
#print(center)
ans = [0 for i in range(n)]
ans[center] = sp[center]
cur = sp[center]
for i in range(center - 1, -1, -1):
cur = min(cur, sp[i])
ans[i] = cur
cur = sp[center]
for i in range(center + 1, n, 1):
cur = min(cur, sp[i])
ans[i] = cur
print(*ans)
``` | output | 1 | 48,959 | 8 | 97,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. | instruction | 0 | 48,960 | 8 | 97,920 |
Tags: data structures, dp, greedy
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=0, func=lambda a, b: 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(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n=int(input())
a=list(map(int,input().split()))
m=a[0]
l=[0]*n
stack=[]
for i in range (n):
m=min(m,a[i])
if m==a[i]:
l[i]=i*a[i]
stack.append(i)
else:
while a[stack[-1]]>a[i]:
stack.pop()
l[i]=a[i]*(i-1-stack[-1])+a[stack[-1]]+l[stack[-1]]
stack.append(i)
#print(l)
r=[0]*n
stack=[]
res=0
m=a[-1]
ind=0
for i in range (n-1,-1,-1):
m=min(m,a[i])
if m==a[i]:
r[i]=(n-1-i)*a[i]
stack.append(i)
else:
while a[stack[-1]]>a[i]:
stack.pop()
r[i]=abs(stack[-1]-i-1)*a[i]+r[stack[-1]]+a[stack[-1]]
stack.append(i)
k=l[i]+r[i]+a[i]
if k>res:
res=k
ind=i
#print(r)
#print(res)
ans=[0]*n
ans[ind]=a[ind]
for i in range (ind+1,n):
ans[i]=min(ans[i-1],a[i])
for i in range (ind-1,-1,-1):
ans[i]=min(ans[i+1],a[i])
print(*ans)
``` | output | 1 | 48,960 | 8 | 97,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal.
Submitted Solution:
```
n=int(input())
inf = int(2e9) + 1
m = [-inf]+[int(x) for x in input().split()] + [-inf]
r = [0] * (n + 2)
st = [0]
for i in range(1, n + 2):
while m[st[-1]] > m[i]:
r[st.pop()] = i
st.append(i)
l = [0] * (n + 2)
st = [0]
for i in range(n+1, 0, -1):
while m[st[-1]] > m[i]:
l[st.pop()] = i
st.append(i)
a=[0]
for i in range(1,n+1):
a.append(a[l[i]]+m[i]*(i-l[i]))
b=[0]*(n+2)
for i in range(n,0,-1):
b[i]=b[r[i]]+m[i]*(r[i]-i)
p=-inf
for i in range(n+1):
t=a[i]+b[i+1]
if t>p:
q=i
p=t
for i in range(q-1,0,-1):
m[i]=min(m[i],m[i+1])
q+=1
for i in range(q+1,n+1):
m[i]=min(m[i],m[i-1])
for i in range(1,n+1):
print(m[i],end=' ')
``` | instruction | 0 | 48,961 | 8 | 97,922 |
Yes | output | 1 | 48,961 | 8 | 97,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal.
Submitted Solution:
```
n = int(input())
m = [-1] + [int(i) for i in input().split()] + [-1]
l = [0] * (n + 2)
r = [0] * (n + 2)
# Π€ΠΎΡΠΌΠΈΡΡΠ΅ΠΌ Π΄Π²Π° ΡΠΏΠΈΡΠΊΠ° Ρ ΠΈΠ½Π΄Π΅ΠΊΡΠ°ΠΌΠΈ Π±Π»ΠΈΠΆΠ°ΠΉΡΠΈΡ
ΠΌΠ΅Π½ΡΡΠΈΡ
ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² ΡΠΏΠ°Π²Π° (ans_right) / ΡΠ»Π΅Π²Π° (ans_left)
ans_right = [0] * (n + 2)
st = [0]
for i in range(1, n + 2):
while m[st[-1]] > m[i]:
ans_right[st.pop()] = i
st.append(i)
ans_left = [0] * (n + 2)
st_2 = [0]
for i in range(n + 1, 0, -1):
while m[st_2[-1]] > m[i]:
ans_left[st_2.pop()] = i
st_2.append(i)
# print('Right:', *ans_right[1:-1])
# print('Left:', *ans_left[1:-1])
for i in range(1, n + 1): # ΠΡΠ΄Π΅ΠΌ ΠΈΡΠΊΠ°ΡΡ Π½Π°ΠΈΠΌΠ΅Π½ΡΡΠΈΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ ΡΠ»Π΅Π²Π°
if ans_left[i] == 0: # ΠΡΠ»ΠΈ m[i] Π½Π°ΠΈΠΌΠ΅Π½ΡΡΠΈΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ ΠΈΠ· Π»Π΅Π²ΡΡ
(Π²ΠΊΠ»ΡΡΠΈΡΠ΅Π»ΡΠ½ΠΎ m[i])
l[i] = i * m[i]
else:
j = ans_left[i]
l[i] = l[j] + (i - j) * m[i]
o = 1
for i in range(n, 0, -1):
if ans_right[i] == n + 1:
r[i] = o * m[i]
# print(i, m[i])
else:
j = ans_right[i]
r[i] = r[j] + (j - i) * m[i]
# print(r[j], (j - i), m[i])
o += 1
maxim = -99999999999
y = 0
for t in range(1, n + 1):
tmp = l[t] + r[t] - m[t]
# print(tmp)
if tmp > maxim:
maxim = tmp
y = t
# print(y - 1)
# print(*l)
# print(*r)
ver = y - 1 # ΠΠ»Ρ ans_left ver + 1 !!!
for i in range(ver - 1, 0, -1):
if m[i] > m[i + 1]:
m[i] = m[i + 1]
# print(*m[1:-1])
# print(m[ver + 1])
for i in range(ver + 2, n + 1):
if m[i] > m[i - 1]:
m[i] = m[i - 1]
print(*m[1:-1])
``` | instruction | 0 | 48,962 | 8 | 97,924 |
Yes | output | 1 | 48,962 | 8 | 97,925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal.
Submitted Solution:
```
import bisect
n=int(input())
a=list(map(int,input().split(' ')))
summ_l=[0]*n
l=[0]*n
left_book_numbers=[0]*n
left_book_indices=[0]*n
summ_l[0]=a[0]
l[0]=a[0]
left_book_numbers[0]=a[0]
left_book_indices[0]=0
p=1
# print(left_book_numbers)
for i in range(1,n):
if(a[i]<=left_book_numbers[0]):
# print('here1:',i)
left_book_numbers[0]=a[i]
left_book_indices[0]=i
p=1
summ_l[i]=(i+1)*(a[i])
elif(left_book_numbers[p-1]<a[i]):
# print('here2:',i)
left_book_numbers[p]=a[i]
left_book_indices[p]=i
summ_l[i]=summ_l[i-1]+a[i]
p+=1
else:
# print('here3',i)
j=bisect.bisect_left(left_book_numbers,a[i],0,p)
summ_l[i]=summ_l[left_book_indices[j-1]]+(i- left_book_indices[j-1] )*a[i]
left_book_numbers[j]=a[i]
left_book_indices[j]=i
p=j+1
# print(left_book_numbers,'pointer:',p)
# print(summ_l)
a.reverse()
summ_r=[0]*n
l=[0]*n
left_book_numbers=[0]*n
left_book_indices=[0]*n
summ_r[0]=a[0]
l[0]=a[0]
left_book_numbers[0]=a[0]
left_book_indices[0]=0
p=1
# print(left_book_numbers)
for i in range(1,n):
if(a[i]<=left_book_numbers[0]):
# print('here1:',i)
left_book_numbers[0]=a[i]
left_book_indices[0]=i
p=1
summ_r[i]=(i+1)*(a[i])
elif(left_book_numbers[p-1]<a[i]):
# print('here2:',i)
left_book_numbers[p]=a[i]
left_book_indices[p]=i
summ_r[i]=summ_r[i-1]+a[i]
p+=1
else:
# print('here3',i)
j=bisect.bisect_left(left_book_numbers,a[i],0,p)
summ_r[i]=summ_r[left_book_indices[j-1]]+(i- left_book_indices[j-1] )*a[i]
left_book_numbers[j]=a[i]
left_book_indices[j]=i
p=j+1
# print(left_book_numbers,'pointer:',p)
summ_r.reverse()
# print(summ_r)
a.reverse()
totals_list=[]
for i in range(n):
totals_list.append(summ_l[i]-a[i]+summ_r[i])
# print(totals_list)
mi=totals_list.index(max(totals_list))
# print(i)
result=[0]*n
result[mi]=a[mi]
i=mi-1
while i>=0:
result[i]=min(result[i+1],a[i])
i-=1
i=mi+1
while i<=n-1:
result[i]=min(result[i-1],a[i])
i+=1
for x in result:
print(x,end=' ')
print()
``` | instruction | 0 | 48,963 | 8 | 97,926 |
Yes | output | 1 | 48,963 | 8 | 97,927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal.
Submitted Solution:
```
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
sys.setrecursionlimit(5*10**5 + 5)
def nxt_smaller(a):
stack = []
ns = [-1]*len(a)
for i in range (n):
while(len(stack)!=0 and stack[-1][0]>a[i]):
curr = stack.pop()
ns[curr[1]]=i
stack.append([a[i],i])
return ns
def prev_smaller(a):
stack = []
a.reverse()
ns = [-1]*len(a)
for i in range (n):
while(len(stack)!=0 and stack[-1][0]>a[i]):
curr = stack.pop()
ns[curr[1]]=n-i-1
stack.append([a[i],i])
a.reverse()
ns.reverse()
return ns
def next(a,i):
if nx[i]!=-1:
return nx[i]
elif ns[i]==-1:
nx[i]=(n-i)*a[i]
return nx[i]
else:
nx[i] = (ns[i]-i)*a[i] + next(a,ns[i])
return nx[i]
def prev(a,i):
if pv[i]!=-1:
return pv[i]
elif ps[i]==-1:
pv[i]=(i+1)*a[i]
return pv[i]
else:
pv[i] = (i-ps[i])*a[i] + prev(a,ps[i])
return pv[i]
n = int(input())
a = [int(i) for i in input().split()]
flag = 0
if a[:50]==[999861030, 999789056, 999746723, 999577696, 999227574, 999132633, 999119425, 998845354, 998825475, 998794950, 998544910, 998524506, 998421426, 998092507, 997867352, 997533517, 997184489, 997161666, 996988824, 996940371, 996781204, 995675803, 995526546, 995264145, 995159880, 994958437, 994899498, 994337095, 994210359, 994132046, 993652562, 993433127, 993432713, 993266971, 993064146, 992793915, 992696607, 992560668, 992517270, 992267996, 992205349, 992039563, 991954593, 991858148, 991641333, 991321684, 990759761, 990434486, 990315553, 990110537]:
flag = 1
ns = nxt_smaller(a)
ps = prev_smaller(a)
nx = [-1]*n
pv = [-1]*n
for i in range (n-1,-1,-1):
if nx[i]==-1:
next(a,i)
for i in range (n):
if pv[i]==-1:
prev(a,i)
maxi = 0
ind = -1
for i in range (n):
curr = nx[i]+pv[i]-a[i]
if curr>maxi:
maxi = curr
ind = i
m = a[ind]
ans = [-1]*n
for i in range (ind,n):
m = min(m,a[i])
ans[i]=m
m = a[ind]
for i in range (ind-1,-1,-1):
m = min(m,a[i])
ans[i]=m
print(*ans)
``` | instruction | 0 | 48,964 | 8 | 97,928 |
Yes | output | 1 | 48,964 | 8 | 97,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal.
Submitted Solution:
```
import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict,deque
import math
def main():
n=int(input())
a=list(map(int,input().split()))
b=[0]*n
ma=0
i=-1
for j in range(n-1,-1,-1):
if ma<a[j]:
ma=a[j]
i=j
b[i]=a[i]
mi=a[i]
j=i-1
while j>=0:
b[j]=min(mi,a[j])
mi=b[j]
j-=1
j =i+1
mi=a[i]
while j<n:
b[j]=min(mi,a[j])
mi = b[j]
j += 1
mi=a[-1]
for i in range(n-2,-1,-1):
a[i]=min(mi,a[i])
if sum(a)>sum(b):
print(*a)
else:
print(*b)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 48,965 | 8 | 97,930 |
No | output | 1 | 48,965 | 8 | 97,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal.
Submitted Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = 10**9
mod = int(1e9)+7
def solve(m):
l=m[::]
stack = [(m[0],0)]
for i in range(1, n):
while stack and stack[-1][0] > m[i]:
stack.pop()
if stack:
v,ind=stack[0]
l[i] = l[ind] + m[i]*(i-ind)
stack.append((m[i], i))
return l
n=int(data())
m=mdata()
l=solve(m)
r=solve(m[::-1])[::-1]
max1=l[0]+r[0]-m[0]
ind=0
for i in range(1,n):
if l[i]+r[i]-m[i]>max1:
max1=l[i]+r[i]-m[i]
ind=i
for i in range(ind-1,-1,-1):
m[i]=min(m[i],m[i+1])
for i in range(ind+1,n):
m[i]=min(m[i],m[i-1])
outl(m)
``` | instruction | 0 | 48,966 | 8 | 97,932 |
No | output | 1 | 48,966 | 8 | 97,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal.
Submitted Solution:
```
n = int(input())
arr = list(map(int, input().split()))
index = arr.index(max(arr))
l = 1
left_max = arr[index]
right_max = arr[index]
res = [0]*n
res[index] = str(arr[index])
while index-l >= 0 or index + l <n :
if index-l >= 0:
left_max = min(arr[index-l], left_max)
res[index-l] = str(left_max)
if index + l < n:
right_max = min(arr[index+l], right_max)
res[index+l] = str(right_max)
l += 1
print(' '.join(res))
``` | instruction | 0 | 48,967 | 8 | 97,934 |
No | output | 1 | 48,967 | 8 | 97,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.
Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.
Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 β€ a_i β€ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.
The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Input
The first line contains a single integer n (1 β€ n β€ 500 000) β the number of plots.
The second line contains the integers m_1, m_2, β¦, m_n (1 β€ m_i β€ 10^9) β the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Output
Print n integers a_i β the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.
If there are multiple answers possible, print any of them.
Examples
Input
5
1 2 3 2 1
Output
1 2 3 2 1
Input
3
10 6 8
Output
10 6 6
Note
In the first example, you can build all skyscrapers with the highest possible height.
In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal.
Submitted Solution:
```
import sys
from math import floor,ceil
import bisect
# from collections import deque
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 30
MOD = 10**7
n = int(ri())
a = Ri()
l = [0]*n
l[0] = a[0]
for i in range(1,len(a)):
if a[i] > a[i-1]:
l[i] = l[i-1]+a[i]
else:
pos = bisect.bisect_left(a,a[i],0,i)
pos-=1
l[i] = l[pos]+(i-pos)*a[i]
r = [0]*n
a = a[::-1]
r[0]= a[0]
for i in range(1,len(a)):
if a[i] > a[i-1]:
r[i] = r[i-1]+a[i]
else:
pos = bisect.bisect_left(a,a[i],0,i)
pos-=1
r[i] = r[pos]+(i-pos)*a[i]
r = r[::-1]
ind = -1
maxx = -1
a = a[::-1]
for i in range(len(a)):
if(l[i]+r[i] -a[i] > maxx):
maxx = l[i]+r[i]-a[i]
ind = i
# print(l,r)
for i in range(ind+1,len(a)):
a[i] = min(a[i-1],a[i])
for i in range(ind-1,-1,-1):
a[i] = min(a[i+1],a[i])
print(*a)
``` | instruction | 0 | 48,968 | 8 | 97,936 |
No | output | 1 | 48,968 | 8 | 97,937 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful. | instruction | 0 | 49,074 | 8 | 98,148 |
Tags: constructive algorithms, data structures, greedy
Correct Solution:
```
import sys
import heapq
input = sys.stdin.readline
def main():
t = int(input())
for _ in range(t):
N, M, X = [int(x) for x in input().split()]
H = [int(x) for x in input().split()]
ans = [0] * N
value = []
for i, v in enumerate(H):
value.append([v, i])
value.sort(reverse=True)
hq = []
for i in range(M):
heapq.heappush(hq, (0, i + 1))
for v, i in value:
ch, cm = heapq.heappop(hq)
heapq.heappush(hq, (ch + v, cm))
ans[i] = cm
ma = 0
mi = float("inf")
while hq:
ci, cm = heapq.heappop(hq)
ma = max(ci, ma)
mi = min(ci, ma)
if abs(ma - mi) <= X:
print("YES")
print(*ans)
else:
print("NO")
if __name__ == '__main__':
main()
``` | output | 1 | 49,074 | 8 | 98,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful. | instruction | 0 | 49,075 | 8 | 98,150 |
Tags: constructive algorithms, data structures, greedy
Correct Solution:
```
T = int(input())
for _ in range(T):
n,m,x = map(int, input().split())
a1 = list(map(int, input().split()))
# print(a1)
a =[]
for i in range(n):
a.append([a1[i], i])
a.sort()
print('YES')
ans = []
weights = []
# print(a)
for i in range(m):
weights.append([0,i])
ans.append([])
i = 0
while(i+m<n):
weights.sort(reverse = True)
# print(weights, i)
for j in range(i,i+m):
# print(weights[j-i][1])
ans[weights[j-i][1]].append(a[j][1])
weights[j-i][0] += a[j][0]
# print(ans)
i+=m
weights.sort()
for j in range(i,n):
ans[weights[j-i][1]].append(a[j][1])
final = [0]*n
count = 0
# print(ans)
for i in ans:
count+=1
# print(i)
for j in i:
final[j] = count
print(*final)
``` | output | 1 | 49,075 | 8 | 98,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful. | instruction | 0 | 49,076 | 8 | 98,152 |
Tags: constructive algorithms, data structures, greedy
Correct Solution:
```
import sys
input = sys.stdin.readline
from heapq import heappop, heappush
for _ in range(int(input())):
# n = int(input())
n, m, x = map(int, input().split())
A = list(map(int, input().split()))
hp = [(0, i) for i in range(m)]
ans = []
for a in A:
b, i = heappop(hp)
ans.append(i + 1)
b += a
heappush(hp, (b, i))
print("YES")
print(*ans)
``` | output | 1 | 49,076 | 8 | 98,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful. | instruction | 0 | 49,077 | 8 | 98,154 |
Tags: constructive algorithms, data structures, greedy
Correct Solution:
```
import sys
from os import path
if(path.exists('input.txt')):
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
# sys.stdin.readline().rstrip()
#n, m = map(int, input().split())
import math
t = int(input())
for _ in range(t):
n, m, x = map(int, input().split())
aa = list(map(int, input().split()))
a = []
for i in range(len(aa)):
a.append((aa[i], i + 1))
a.sort()
towers = [0] * m
idx = [-1] * n
"""
n, m, and x
"""
for i in range(n):
tw = i % m
idx[a[i][1] - 1] = tw + 1
towers[tw] += a[i][0]
"""
print('a =', a)
print('idx =', idx)
print('towers =', towers)
"""
if(max(towers) - min(towers) <= x):
print("YES")
print(' '.join(map(str, idx)))
else:
print("NO")
``` | output | 1 | 49,077 | 8 | 98,155 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful. | instruction | 0 | 49,078 | 8 | 98,156 |
Tags: constructive algorithms, data structures, greedy
Correct Solution:
```
t = int(input())
for case in range(1, t+1):
n, m, x = (int(i) for i in input().split())
h = [int(i) for i in input().split()]
blocks = [[h[i], i, 0] for i in range(n)]
blocks.sort(key=lambda x: x[0], reverse=True)
towerHeights = [0 for _ in range(m)]
t = 0
for b in blocks:
b[2] = t+1
towerHeights[t] += b[0]
t = (t+1) % m
blocks.sort(key=lambda x:x[1])
if (max(towerHeights) - min(towerHeights) <= x):
print("YES")
for b in blocks:
print(b[2], end = " ")
print()
else:
print("NO")
``` | output | 1 | 49,078 | 8 | 98,157 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful. | instruction | 0 | 49,079 | 8 | 98,158 |
Tags: constructive algorithms, data structures, greedy
Correct Solution:
```
from heapq import heappush, heappop
def putin():
return map(int, input().split())
def sol():
n, m, x = putin()
A = list(putin())
H = []
if n < m:
print("NO")
return
print("YES")
for i in range(m):
heappush(H, (0, i + 1))
for elem in A:
a, b = heappop(H)
print(b, end=' ')
heappush(H, (a + elem, b))
print()
for iter in range(int(input())):
sol()
``` | output | 1 | 49,079 | 8 | 98,159 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful. | instruction | 0 | 49,080 | 8 | 98,160 |
Tags: constructive algorithms, data structures, greedy
Correct Solution:
```
import io,os
import sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def solve_tc():
n, m, x = map(int, input().split())
s = list(map(int, input().split()))
ans = [0 for i in range(n)]
l = []
for i in range(len(s)):
l.append([s[i], i])
l.sort(key=lambda val: val[0])
a = 1
for i in l:
ans[i[1]] = a
a += 1
if a > m:
a = 1
return ans
t = int(input())
while t > 0:
t -= 1
m = solve_tc()
print("YES")
sys.stdout.write(" ".join(map(str, m)))
sys.stdout.write("\n")
``` | output | 1 | 49,080 | 8 | 98,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful. | instruction | 0 | 49,081 | 8 | 98,162 |
Tags: constructive algorithms, data structures, greedy
Correct Solution:
```
import os, sys, math
from io import BytesIO, IOBase
ma = lambda: map(int, input().split(" "))
def main():
for _ in range(int(input())):
n, m, x = ma()
h = list(ma())
hl = []
for i in range(n):
hl.append([h[i], i + 1])
hl.sort()
f = True
a = [0] * m
index = [0] * n
for i in range(n):
a[i%m] += hl[i][0]
index[hl[i][1] - 1] = (i%m) + 1
if max(a) - min(a) <= x:
f = False
if f:
print("NO")
continue
print("YES")
print(*index)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | output | 1 | 49,081 | 8 | 98,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful.
Submitted Solution:
```
from sys import stdin, stdout
from math import sqrt, inf, hypot
from copy import copy
# from random import randint
from heapq import heappop, heapify, heappush
from _collections import deque
t = int(stdin.readline())
for _ in range(t):
# n = int(stdin.readline())
n, m, k = map(int, stdin.readline().split())
a = [int(x) for x in stdin.readline().split()]
for i in range(n):
a[i] = (a[i], i)
a.sort(key= lambda p: p[0], reverse=True)
ans = [-1] * n
heap = []
for i in range(m):
heap.append((0, i))
heapify(heap)
for i in range(n):
cnt, tower = heappop(heap)
cost, num = a[i]
ans[num] = tower
heappush(heap, (cnt+cost, tower))
mn = 1e12
mx = 0
#print(*heap, k)
for x in heap:
#print(x)
if x[0] < mn: mn = x[0]
if x[0] > mx: mx = x[0]
#print(mx, mn)
if mx - mn <= k:
stdout.write("YES\n")
for i in ans:
stdout.write(str(i+1)+" ")
stdout.write("\n")
else:
stdout.write("NO\n")
# b = [int(x) for x in stdin.readline().split()]
``` | instruction | 0 | 49,082 | 8 | 98,164 |
Yes | output | 1 | 49,082 | 8 | 98,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful.
Submitted Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def main():
from heapq import heappush, heappop
for _ in range(int(input())):
n,m,x = map(int,input().split())
a = list(map(int,input().split()))
towerHeight = [0] * m
loc = []
h = []
for i in range(m):
heappush(h, (0, i))
for i in range(n):
c = heappop(h)
loc.append(c[1] + 1)
towerHeight[c[1]] += a[i]
heappush(h, (towerHeight[c[1]], c[1]))
print("YES")
print(" ".join(map(str, loc)))
# 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 | 49,083 | 8 | 98,166 |
Yes | output | 1 | 49,083 | 8 | 98,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful.
Submitted Solution:
```
# cook your dish here
def indsort(s):
li=[]
for i in range(len(s)):
li.append([s[i],i])
li.sort()
sort_index = []
for x in li:
sort_index.append(x[1])
return sort_index
t=int(input())
for _ in range(t):
#n=int(input())
n,m,x = map(int,input().split())
h = list(map(int,input().split()))
ind = indsort(h)
ans=[0]*n
hei = [0]*m
for i in range(n):
if (i+1)%m==0:
mod=m
else:
mod=(i+1)%m
ans[ind[i]] = mod
hei[mod-1]+=h[ind[i]]
if max(hei)-min(hei)>x:
print('NO')
else:
print('YES')
print(*ans)
``` | instruction | 0 | 49,084 | 8 | 98,168 |
Yes | output | 1 | 49,084 | 8 | 98,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful.
Submitted Solution:
```
for _ in range(int(input())):
n,m,x=map(int,input().split())
q=list(map(int,input().split()))
q=[(q[i],i) for i in range(n)]
q.sort()
ans=[None]*n
for i in range(n): ans[q[i][1]]=i%m
print('YES')
for i in ans: print(i+1,end=' ')
print()
``` | instruction | 0 | 49,085 | 8 | 98,170 |
Yes | output | 1 | 49,085 | 8 | 98,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful.
Submitted Solution:
```
t=int(input())
for i in range(t):
n,m,x=map(int,input().split())
a=list(map(int,input().split()))
b=sorted(a)
c=[0]*m
final=[]
for i in range(n):
nfi=i%m
nfi+=1
final.append(nfi)
for i in range(len(b)):
c[i%m]+=b[i]
if (max(c)-min(c))<=x:
print("YES")
print(*final)
else:
print("NO")
``` | instruction | 0 | 49,086 | 8 | 98,172 |
No | output | 1 | 49,086 | 8 | 98,173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful.
Submitted Solution:
```
from bisect import insort_left as ins
t = int(input())
for _ in range(t):
n, m, xx = map(int, input().split())
h = list(map(int, input().split()))
h = [(h[i], (i,)) for i in range(n)]
h.sort()
#print(h)
while len(h) > m:
x = h[0]
y = h[1]
h = h[2:]
ins(h, (x[0]+y[0], x[1]+y[1]))
#print(h)
flag = True
#if h[-1][0] > h[0][0] + xx: flag = False
#if not flag:
#print("NO")
#continue
print("YES")
ans = [0 for i in range(n)]
i = 1
for ele in h:
for el in ele[1]: ans[el] = i
i += 1
print(" ".join([str(x) for x in ans]))
``` | instruction | 0 | 49,087 | 8 | 98,174 |
No | output | 1 | 49,087 | 8 | 98,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful.
Submitted Solution:
```
def ii():
return int(input())
def li():
return [int(i) for i in input().split()]
for t in range(ii()):
n,m,x = li()
h = li()
h.sort()
ans = [0 for i in range(n)]
for i in range(n):
ans[i] = i%m+1
print(*ans)
``` | instruction | 0 | 49,088 | 8 | 98,176 |
No | output | 1 | 49,088 | 8 | 98,177 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains three integers n, m, and x (1 β€ m β€ n β€ 10^5; 1 β€ x β€ 10^4) β the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.
The second line of each test case contains n space-separated integers (1 β€ h_i β€ x) β the heights of the blocks.
It is guaranteed that the sum of n over all the test cases will not exceed 10^5.
Output
For each test case, if Phoenix cannot build m towers that look beautiful, print NO. Otherwise, print YES, followed by n integers y_1, y_2, ..., y_n, where y_i (1 β€ y_i β€ m) is the index of the tower that the i-th block is placed in.
If there are multiple solutions, print any of them.
Example
Input
2
5 2 3
1 2 3 1 2
4 3 3
1 1 2 3
Output
YES
1 1 1 2 2
YES
1 2 2 3
Note
In the first test case, the first tower has height 1+2+3=6 and the second tower has height 1+2=3. Their difference is 6-3=3 which doesn't exceed x=3, so the towers are beautiful.
In the second test case, the first tower has height 1, the second tower has height 1+2=3, and the third tower has height 3. The maximum height difference of any two towers is 3-1=2 which doesn't exceed x=3, so the towers are beautiful.
Submitted Solution:
```
from os import path
import sys,time, collections as c , math , pprint as p , itertools as it , operator as op , bisect as bs
maxx , localsys , mod = float('inf'), 0 , int(1e9 + 7)
if (path.exists('input.txt')): sys.stdin=open('input.txt','r') ; sys.stdout=open('output.txt','w')
input = sys.stdin.readline
for _ in range(int(input())):
n , m , x = map(int , input().split())
a = list(map(int , input().split()))
d = c.defaultdict(list)
for i in range(n):
d[a[i]].append(i)
a.sort()
i , j , avg = 0 , n - 1 , n//m
st , p = [0]*n , []
num = 1
if avg == 1:
while i< n and i < j and j >= 0:
if m - num >=1 and num % 2 :
cnt =0 ; su= 0
while i < n and cnt < avg:
st[d[a[i]].pop(0)] = num
su+=a[i]
i+=1 ; cnt+=1
num+=1
p.append(su)
if m - num >= 1 and num % 2 == 0:
cnt =0 ; su =0
while j >= 0 and cnt < avg and i < j:
st[d[a[j]].pop(0)] = num
su+=a[j]
j-=1 ; cnt+=1
num+=1
p.append(su)
elif m -num == 0:
su =0
while i <= j :
st[d[a[i]].pop(0)] = num
su+=a[i]
i+=1
p.append(su)
num+=1
else:
while i < n and i < j and j >=0:
cnt , su = 0 , 0
if m - num >=1:
while cnt < avg and i <= j:
su+=a[i]
st[d[a[i]].pop(0)] = num
cnt+=1
i+=1
if cnt == avg:
break
su+=a[j]
st[d[a[j]].pop(0)] = num
j-=1
cnt+=1
p.append(su)
num+=1
else:
while i <= j:
su+=a[i]
st[d[a[i]].pop(0)] = num
i+=1
num+=1
p.append(su)
ok = True
for i in range(len(p)):
for j in range(len(p)):
if i != j :
if abs(p[i] - p[j]) > x:
ok = False
break
if not ok:
break
if ok :
print('YES')
else:
print('NO')
# for _ in range(int(input())):
# n = int(input())
# a , i , j ,ok = [[int(i) for i in input().rstrip('\n')] for _ in range(2)] , 0 , 0 , True
# while j < n :
# if a[i][j] > 2:
# if a[i^1][j] < 3:
# break
# else:
# i^=1
# j+=1
# print('YES' if i==1 and j == n else 'NO')
#for example suppose if you are at row 1 and standing on the curled tile which will obviously lead to another row
#and if this row has ( | or - ) then obviously you have no other way to move forward
#all other combinations are viable
# n = int(input()) ; g = c.defaultdict(list)
# for _ in range(n-1):
# u , v = map(int , input().split())
# g[u].append(v)
# g[v].append(u)
# v , q , ans = [0]*(n+1) , [(1 ,1 ,0)] , 0 #p , cnt , height
# while q :
# p , cnt , h = q.pop()
# v[p] , c = 1 , 0
# for i in g[p]:
# if not v[i]:
# c+=1
# if c == 0 :
# ans+= cnt*h
# else:
# for i in g[p]:
# if not v[i]:
# q.append((i , cnt/c , h+1))
# v[i] = 1
# print(q,ans , p, cnt , h)
# print('%.14f'%(ans))
# #probability of the horse taking the route to each of the child of the parent * length of the journey = expected value for that vertex
# def ok(p , s):
# cnt , need =0 , 0
# for i in s:
# if p[need] == i:
# cnt+=1 ; need ^= 1
# if cnt % 2 and p[0] != p[1]:
# cnt-=1
# return cnt
# for _ in range(int(input())):
# s = input().rstrip('\n') ; n , ans = len(s) , maxx
# for i in range(10):
# for j in range(10):
# ans = min(ans , n - ok((str(i) , str(j)), s))
# print(ans)
#This problem was so easy oh gawd , so you can only make left cyclic shift = right cyclic shift , when there are at most
#2 characters
#(incase of 1 ch) at the same time if total string has only character it is valid no matter how you see it
#(incase of 2 ch) all the characters at odd positions must be equal , and all the characters at even position must be equal
# n , k = map(int , input().split()) ; s = input().rstrip('\n')
# ans = a = b = j = 0
# for i in range(n):
# a , b = (a+1 , b) if s[i] == 'a' else (a , b+1 )
# if min(a, b) > k :
# a , b = (a -1 , b) if s[j] == 'a' else (a , b -1) ; j+=1
# else:
# ans+=1
# print(ans)
# #two - pointer method , if at any point min(a , b )> k then keep on decreasing from the beginning untill and unless you get min(a , b)
# #less than k
``` | instruction | 0 | 49,089 | 8 | 98,178 |
No | output | 1 | 49,089 | 8 | 98,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·108) and integer m (1 β€ m β€ 20). The i + 1-th line contains a pair of numbers ai and bi (1 β€ ai β€ 108, 1 β€ bi β€ 10). All the input numbers are integer.
Output
Output the only number β answer to the problem.
Examples
Input
7 3
5 10
2 5
3 6
Output
62
Input
3 3
1 3
2 2
3 1
Output
7
Submitted Solution:
```
n,m = map(int,input().split())
t = []
for _ in range(m):
t.append([int(i) for i in reversed(input().split())])
t.sort()
d=0
for i in range(len(t)-1,-1,-1):
x = min(t[i][1],n)
n = n - x
d += x*t[i][0]
print(d)
``` | instruction | 0 | 49,114 | 8 | 98,228 |
Yes | output | 1 | 49,114 | 8 | 98,229 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·108) and integer m (1 β€ m β€ 20). The i + 1-th line contains a pair of numbers ai and bi (1 β€ ai β€ 108, 1 β€ bi β€ 10). All the input numbers are integer.
Output
Output the only number β answer to the problem.
Examples
Input
7 3
5 10
2 5
3 6
Output
62
Input
3 3
1 3
2 2
3 1
Output
7
Submitted Solution:
```
from bisect import bisect_right as br
import sys
from collections import *
from math import *
import re
def sieve(n):
prime=[True for i in range(n+1)]
p=2
while p*p<=n:
if prime[p]==True:
for i in range(p*p,n+1,p):
prime[i]=False
p+=1
c=0
for i in range(2,n):
if prime[i]:
#print(i)
c+=1
return c
def totient(n):
res,p=n,2
while p*p<=n:
if n%p==0:
while n%p==0:
n=n//p
res-=int(res/p)
p+=1
if n>1:res-=int(res/n)
return res
def iseven(n):return[False,True][0 if n%2 else 1]
def inp_matrix(n):return list([input().split()] for i in range(n))
def inp_arr():return list(map(int,input().split()))
def inp_integers():return map(int,input().split())
def inp_strings():return input().split()
def lcm(a,b):return (a*b)/gcd(a,b)
max_int = sys.maxsize
mod = 10**9+7
flag1=False
flag2=False
n,m=inp_integers()
L=[list(map(int,input().split())) for i in range(m)]
L.sort(key=lambda x:x[1],reverse=True)
#print(L)
ans=0
for i in range(m):
ans+=min(L[0][0],n)*L[0][1]
n-=min(L[0][0],n)
L.pop(0)
print(ans)
``` | instruction | 0 | 49,115 | 8 | 98,230 |
Yes | output | 1 | 49,115 | 8 | 98,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·108) and integer m (1 β€ m β€ 20). The i + 1-th line contains a pair of numbers ai and bi (1 β€ ai β€ 108, 1 β€ bi β€ 10). All the input numbers are integer.
Output
Output the only number β answer to the problem.
Examples
Input
7 3
5 10
2 5
3 6
Output
62
Input
3 3
1 3
2 2
3 1
Output
7
Submitted Solution:
```
def q16b():
n, m = tuple([int(num) for num in input().split()])
as_ = []
bs_ = []
for _ in range(m):
a, b = tuple([int(num) for num in input().split()])
as_.append(a)
bs_.append(b)
argsorted = sorted(range(len(bs_)), key=bs_.__getitem__)
argsorted.reverse()
total = 0
for i in range(len(argsorted)):
if(n <= 0):
break
total += min(as_[argsorted[i]], n) * bs_[argsorted[i]]
n -= as_[argsorted[i]]
print(total)
q16b()
# def q16b():
# n, m = tuple([int(num) for num in input().split()])
# boxes = []
# for _ in range(m):
# a, b = tuple([int(num) for num in input().split()])
# boxes = boxes + [b for _ in range(a)]
# boxes.sort()
# boxes.reverse()
# print(sum(boxes[:n]))
# q16b()
``` | instruction | 0 | 49,116 | 8 | 98,232 |
Yes | output | 1 | 49,116 | 8 | 98,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·108) and integer m (1 β€ m β€ 20). The i + 1-th line contains a pair of numbers ai and bi (1 β€ ai β€ 108, 1 β€ bi β€ 10). All the input numbers are integer.
Output
Output the only number β answer to the problem.
Examples
Input
7 3
5 10
2 5
3 6
Output
62
Input
3 3
1 3
2 2
3 1
Output
7
Submitted Solution:
```
import sys
import math
import collections
import heapq
input=sys.stdin.readline
n,m=(int(i) for i in input().split())
d={}
for i in range(m):
a,b=(int(i) for i in input().split())
if(b in d):
d[b]+=a
else:
d[b]=a
d1=dict(collections.OrderedDict(sorted(d.items(),reverse=True)))
c=0
c1=0
for i in d1:
if(c1+d1[i]<=n):
c1+=d1[i]
c+=i*d1[i]
else:
c+=(n-c1)*i
c1=n
print(c)
``` | instruction | 0 | 49,117 | 8 | 98,234 |
Yes | output | 1 | 49,117 | 8 | 98,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·108) and integer m (1 β€ m β€ 20). The i + 1-th line contains a pair of numbers ai and bi (1 β€ ai β€ 108, 1 β€ bi β€ 10). All the input numbers are integer.
Output
Output the only number β answer to the problem.
Examples
Input
7 3
5 10
2 5
3 6
Output
62
Input
3 3
1 3
2 2
3 1
Output
7
Submitted Solution:
```
n,m=map(int,input().split())
ai=[]
k=0
v=0
for i in range(m):
a,b=map(int,input().split())
ai.append([b,a])
ai = sorted(ai)[::-1]
for i in ai:
print(i[0])
v=min(i[1],n)
n-=v
k+=(v*i[0])
print(k)
``` | instruction | 0 | 49,118 | 8 | 98,236 |
No | output | 1 | 49,118 | 8 | 98,237 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·108) and integer m (1 β€ m β€ 20). The i + 1-th line contains a pair of numbers ai and bi (1 β€ ai β€ 108, 1 β€ bi β€ 10). All the input numbers are integer.
Output
Output the only number β answer to the problem.
Examples
Input
7 3
5 10
2 5
3 6
Output
62
Input
3 3
1 3
2 2
3 1
Output
7
Submitted Solution:
```
n,m = map(int,input().split())
f=[]
for k in range(m):
f.append(list(map(int,input().split()))[::-1])
f.sort()
g=f[::-1]
p=0
while n:
for u in g:
if u[1]<=n:
p+=u[1]*(u[0])
n-=u[1]
elif u[1]>n:
p+= u[0]*n
n=0
print(p)
``` | instruction | 0 | 49,119 | 8 | 98,238 |
No | output | 1 | 49,119 | 8 | 98,239 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·108) and integer m (1 β€ m β€ 20). The i + 1-th line contains a pair of numbers ai and bi (1 β€ ai β€ 108, 1 β€ bi β€ 10). All the input numbers are integer.
Output
Output the only number β answer to the problem.
Examples
Input
7 3
5 10
2 5
3 6
Output
62
Input
3 3
1 3
2 2
3 1
Output
7
Submitted Solution:
```
def cost(arr):
return arr[1]/arr[0]
def knap(arr,n):
items=sorted(arr,key=cost)
ans=0
print(items)
for i in items:
wt,co=i[0],i[1]
if(wt<=n):
n-=wt
ans+=wt*co
else:
ans+=(n)*co
break
return ans
tt=list(map(int,input().split()))
arr=[]
for i in range(tt[1]):
arr1=list(map(int,input().split()))
arr.append(arr1)
print(knap(arr,tt[0]))
``` | instruction | 0 | 49,120 | 8 | 98,240 |
No | output | 1 | 49,120 | 8 | 98,241 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·108) and integer m (1 β€ m β€ 20). The i + 1-th line contains a pair of numbers ai and bi (1 β€ ai β€ 108, 1 β€ bi β€ 10). All the input numbers are integer.
Output
Output the only number β answer to the problem.
Examples
Input
7 3
5 10
2 5
3 6
Output
62
Input
3 3
1 3
2 2
3 1
Output
7
Submitted Solution:
```
n, m = [int(x) for x in input().split()]
cont = []
tot = 0
for i in range(m):
a, b = map(int, input().split())
cont.append([a,b])
cont = sorted(cont, key = lambda x : x[1])
while n > 0 and cont:
if n>= cont[-1][0]:
tot += (cont[-1][1] * cont[-1][0])
n -= cont[-1][0]
else:
tot += (cont[-1][1] * n)
cont.pop()
print(tot)
``` | instruction | 0 | 49,121 | 8 | 98,242 |
No | output | 1 | 49,121 | 8 | 98,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4. | instruction | 0 | 49,334 | 8 | 98,668 |
Tags: brute force, data structures, dp, greedy, sortings
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
n = int(input())
a,b,h = [],[],[]
for _ in range(n):
u1,v1,w1 = map(int,input().split())
a.append(u1)
b.append(v1)
h.append(w1)
rr = sorted(sorted(range(n),key=lambda yy:a[yy]),key=lambda xx:b[xx])
dp,st = [0]*n,[n]*n
for ind in range(n-1,-1,-1):
i,y = rr[ind],ind+1
while y != n and a[i] <= a[rr[y]]:
y = st[y]
st[ind] = y
for ind in range(n-1,-1,-1):
i,y = rr[ind],ind+1
while y != n and b[i] <= a[rr[y]]:
y = st[y]
dp[ind] = h[i]+(0 if y == n else dp[y])
print(max(dp))
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 49,334 | 8 | 98,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4. | instruction | 0 | 49,335 | 8 | 98,670 |
Tags: brute force, data structures, dp, greedy, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd
from collections import deque
import bisect
import heapq
# import sys
# input = sys.stdin.readline
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
class segmentTree:
def __init__(self, n):
self.n = n
self.tree = [0] * (2 * self.n)
def update(self, p, value):
self.tree[self.n + p] = value
p = p + self.n
while p > 1:
self.tree[p >> 1] = max(self.tree[p], self.tree[p ^ 1])
p >>= 1
def min(self, l, r):
res = 0
l += self.n
r += self.n
while l < r:
if (l & 1):
res = max(res, self.tree[l])
l += 1
if r & 1:
r -= 1
res = max(res, self.tree[r])
l >>= 1
r >>= 1
return res
def solve():
n = ri()
disks = []
A = set()
for i in range(n):
a, b, h = rl()
disks.append([b, a, h])
A.add(a)
disks.sort(reverse=True)
AS = sorted(list(A))
xref = {a: i for (i, a) in enumerate(AS)}
def bi(b):
return bisect.bisect_left(AS, b)
T = segmentTree(n)
for b, a, h in disks:
prev = T.min(0, bi(b))
local = h + prev
T.update(xref[a], local)
# print (a, b, h, ":", local)
# print (T.tree)
print (T.min(0, n))
mode = 's'
if mode == 'T':
t = ri()
for i in range(t):
solve()
else:
solve()
``` | output | 1 | 49,335 | 8 | 98,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4. | instruction | 0 | 49,336 | 8 | 98,672 |
Tags: brute force, data structures, dp, greedy, sortings
Correct Solution:
```
import sys
n = int(sys.stdin.readline())
valores = [sys.stdin.readline().strip().split(' ') for _ in range(n)]
tmp = [0]*n
stack = []
#print(valores)
valores.sort(key=lambda x: (int(x[1]), int(x[0])), reverse=True)
for i in range(n):
while len(stack) > 0 and int(valores[stack[-1]][0]) >= int(valores[i][1]):
stack.pop()
if len(stack) > 0:
tmp[i] = tmp[stack[-1]] + int(valores[i][2])
else :
tmp[i] += int(valores[i][2])
stack.append(i)
sys.stdout.write(str(max(tmp))+'\n')
``` | output | 1 | 49,336 | 8 | 98,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4. | instruction | 0 | 49,337 | 8 | 98,674 |
Tags: brute force, data structures, dp, greedy, sortings
Correct Solution:
```
aux = [(9e9, 0, 0)]
n = int(input())
for i in range(n):
a, b, h = map(int, input().split())
aux.append((b, a, h)) #sort padrao eh pelo item 0 da tupla
aux.sort(reverse=True)
s, p = [0], [0] *(n + 1)
for i in range(1, n + 1):
while aux[s[-1]][1] >= aux[i][0]:
s.pop()
p[i] = p[s[-1]] + aux[i][2]
s.append(i)
print(max(p))
``` | output | 1 | 49,337 | 8 | 98,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4. | instruction | 0 | 49,338 | 8 | 98,676 |
Tags: brute force, data structures, dp, greedy, sortings
Correct Solution:
```
n = int(input())
d = []
for i in range(n):
a, b, h = map(int, input().split())
d.append((b, a, h))
d.sort()
ht = d[len(d) - 1][2]
ans = ht
s = []
s.append(d[len(d) - 1])
for i in range(n - 2, -1, -1):
while s and d[i][0] <= s[len(s) - 1][1]:
ht -= s.pop()[2]
s.append(d[i])
ht += d[i][2]
if ans < ht:
ans = ht
print(ans)
``` | output | 1 | 49,338 | 8 | 98,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4. | instruction | 0 | 49,339 | 8 | 98,678 |
Tags: brute force, data structures, dp, greedy, sortings
Correct Solution:
```
from sys import stdin
n=int(input())
x,ans,sum=[[0]*3 for i in range(n)],0,0
d=[]
for i in range(n):
x[i][1],x[i][0],x[i][2]=map(int,stdin.readline().split())
x.sort()
for i in range(n-1,-1,-1):
while len(d)>0 and d[len(d)-1][1]>=x[i][0]:
sum-=d[len(d)-1][2]
d.pop()
d.append(x[i])
sum+=x[i][2]
ans=max(ans,sum)
print(ans)
``` | output | 1 | 49,339 | 8 | 98,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4. | instruction | 0 | 49,340 | 8 | 98,680 |
Tags: brute force, data structures, dp, greedy, sortings
Correct Solution:
```
import sys
n = int(sys.stdin.readline())
valores = [sys.stdin.readline().strip().split(' ') for _ in range(n)]
valores.sort(key=lambda x: (int(x[1]), int(x[0])), reverse=True)
tmp = [0]*n
stack = []
#print(valores)
for i in range(len(valores)):
while len(stack) > 0 and int(valores[stack[-1]][0]) >= int(valores[i][1]):
stack.pop()
if len(stack) > 0:
tmp[i] = tmp[stack[-1]] + int(valores[i][2])
stack.append(i)
else :
tmp[i] += int(valores[i][2])
stack.append(i)
sys.stdout.write(str(max(tmp))+'\n')
``` | output | 1 | 49,340 | 8 | 98,681 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4. | instruction | 0 | 49,341 | 8 | 98,682 |
Tags: brute force, data structures, dp, greedy, sortings
Correct Solution:
```
n = int(input())
d = []
for i in range(n):
a, b, h = map(int, input().split())
d.append((b, a, h))
d.sort()
ht = d[len(d) - 1][2]
ans = ht
s = [d[len(d) - 1]]
for i in range(n - 2, -1, -1):
while s and d[i][0] <= s[len(s) - 1][1]:
ht -= s.pop()[2]
s.append(d[i])
ht += d[i][2]
if ans < ht:
ans = ht
print(ans)
``` | output | 1 | 49,341 | 8 | 98,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4.
Submitted Solution:
```
t = [(9e9, 0, 0)]
n = int(input())
for i in range(n):
a, b, h = map(int, input().split())
t.append((b, a, h))
t.sort(reverse=True)
s, p = [0], [0] * (n + 1)
for i in range(1, n + 1):
while t[s[-1]][1] >= t[i][0]: s.pop()
p[i] = p[s[-1]] + t[i][2]
s.append(i)
print(max(p))
``` | instruction | 0 | 49,342 | 8 | 98,684 |
Yes | output | 1 | 49,342 | 8 | 98,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4.
Submitted Solution:
```
import operator
n = int(input())
arr=[]
for i in range(n):
arr.append([int(element) for element in input().split()])
arr = sorted(arr, key=operator.itemgetter(1,0,2), reverse= True)
heigh = [0 for i in range(n)]
seq = []
for i in range(n):
while len(seq) > 0 and arr[seq[-1]][0] >= arr[i][1] :
seq.pop()
if len(seq) > 0 :
heigh[i] = heigh[seq[-1]]
heigh[i] += arr[i][2]
seq.append(i)
print(max(heigh))
``` | instruction | 0 | 49,343 | 8 | 98,686 |
Yes | output | 1 | 49,343 | 8 | 98,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
* Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj β€ bi.
* Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
* The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 β€ ai, bi, hi β€ 109, bi > ai) β inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer β the maximum height of the tower that can be obtained.
Examples
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
Note
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4.
Submitted Solution:
```
from collections import defaultdict as dd
from collections import deque
import bisect
import heapq
import sys
input = sys.stdin.readline
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
class segmentTree:
def __init__(self, n):
self.n = n
self.tree = [0] * (2 * self.n)
def update(self, p, value):
self.tree[self.n + p] = value
p = p + self.n
while p > 1:
self.tree[p >> 1] = max(self.tree[p], self.tree[p ^ 1])
p >>= 1
def min(self, l, r):
res = 0
l += self.n
r += self.n
while l < r:
if (l & 1):
res = max(res, self.tree[l])
l += 1
if r & 1:
r -= 1
res = max(res, self.tree[r])
l >>= 1
r >>= 1
return res
def solve():
n = ri()
disks = []
A = set()
for i in range(n):
a, b, h = rl()
disks.append([b, a, h])
A.add(a)
disks.sort(reverse=True)
AS = sorted(list(A))
xref = {a: i for (i, a) in enumerate(AS)}
def bi(b):
return bisect.bisect_left(AS, b)
T = segmentTree(n)
for b, a, h in disks:
prev = T.min(0, bi(b))
local = h + prev
T.update(xref[a], local)
# print (a, b, h, ":", local)
# print (T.tree)
print (T.min(0, n))
mode = 's'
if mode == 'T':
t = ri()
for i in range(t):
solve()
else:
solve()
``` | instruction | 0 | 49,344 | 8 | 98,688 |
Yes | output | 1 | 49,344 | 8 | 98,689 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.