input stringlengths 20 127k | target stringlengths 20 119k | problem_id stringlengths 6 6 |
|---|---|---|
import math
import collections
import itertools
import sys
import bisect
from heapq import heappop,heappush,heapify
sys.setrecursionlimit(10**6)
def MAP(): return list(map(int,input().split()))
def INT(): return int(eval(input()))
def FLOAT(): return float(eval(input()))
MOD = 10**9+7
n,m = MAP()
a = MAP()
heapify(a)
d = []
for i in range(m):
b,c = MAP()
d += [c]*b
d.sort(reverse=True)
while 1:
tmp = heappop(a)
if tmp<d[0]:
heappush(a,d.pop(0))
else:
a+=[tmp]
break
if len(d)==0:
break
print((sum(a))) | import math
import collections
import itertools
import sys
import bisect
from heapq import heappop,heappush,heapify
sys.setrecursionlimit(10**6)
def MAP(): return list(map(int,input().split()))
def INT(): return int(eval(input()))
def FLOAT(): return float(eval(input()))
MOD = 10**9+7
n, m = MAP()
a = MAP()
p = [(a[i], 1) for i in range(n)]
for j in range(m):
b, c = MAP()
p.append((c, b))
p.sort(reverse=True)
ans, cnt = 0, n
for (v, c) in p:
use = min(c, cnt)
ans += use * v
cnt -= use
print(ans) | p03038 |
from heapq import (
heapify, # 優先度付きキューの生成
heappop, # キューから値を取り出す
heappush, # キューに値を格納
heappushpop, # push -> popの順
heapreplace, # pop -> pushの順
)
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
A = [-i for i in A]
bc = []
for _ in range(M):
B, C = list(map(int, input().split()))
bc.extend([-C]*B)
A = A + bc
heapify(A)
total = 0
for _ in range(N):
total += -heappop(A)
print(total) | N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
dic = {}
for i in range(N):
tmp = A[i]
if tmp in dic:
dic[tmp] += 1
else:
dic[tmp] = 1
for _ in range(M):
B, C = list(map(int, input().split()))
if C in dic:
dic[C] += B
else:
dic[C] = B
dic = sorted(list(dic.items()), reverse=True)
ans, cnt = 0, 0
i = 0
while True:
k, v = dic[i]
cnt += v
if cnt < N:
ans += k*v
elif cnt == N:
ans += k*v
break
else:
ans += k*(v - (cnt-N))
break
i += 1
print(ans) | p03038 |
n,m = list(map(int,input().split()))
a = list(map(int,input().split()))
bc = [list(map(int,input().split())) for _ in range(m)]
bc = sorted(bc,key=lambda x:(x[1]))
count=0
for b,c in bc:
count += b
a.extend([c]*b)
if b > n:
break
print((sum(sorted(a,reverse=True)[:n]))) | n,m = list(map(int,input().split()))
a = list(map(int,input().split()))
bc = [list(map(int,input().split())) for _ in range(m)]
bc = sorted(bc,key=lambda x:(x[1]),reverse=True)
count=0
for b,c in bc:
count += b
a.extend([c]*b)
if count >= n:
break
print((sum(sorted(a,reverse=True)[:n]))) | p03038 |
import sys
import heapq
input = sys.stdin.readline
n,m = list(map(int,input().split()))
heap = [int(i) for i in input().split()]
heap.sort()
for i in range(m):
a,b = list(map(int,input().split()))
for j in range(a):
if heap[0] < b:
heapq.heappop(heap)
heapq.heappush(heap,b)
print((sum(heap))) | import sys
input = sys.stdin.readline
n,m = list(map(int,input().split()))
heap = [int(i) for i in input().split()]
heap.sort()
ans = sum(heap)
ml = []
cnt = 0
for i in range(m):
a,b = list(map(int,input().split()))
ml += [[b,a]]
ml.sort(reverse=True)
for i in range(m):
for j in range(ml[i][1]):
if ml[i][0] > heap[cnt]:
ans += ml[i][0] - heap[cnt]
cnt += 1
if cnt == n:
print(ans)
exit()
else:
print(ans)
exit()
print(ans) | p03038 |
import sys
def input():
return sys.stdin.readline()[:-1]
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
BC_list = []
for i in range(M):
B, C = list(map(int, input().split()))
BC_list.append({
'B': B,
'C': C
})
BC_list.sort(reverse=True, key=lambda x: x['C'])
A_last = min(A)
for pair in BC_list:
if pair['C'] < A_last:
break
for _ in range(pair['B']):
A.append(pair['C'])
A.sort(reverse=True)
print((sum(A[0:N])))
| import sys
def input():
return sys.stdin.readline()[:-1]
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
BC_list = []
for i in range(M):
B, C = list(map(int, input().split()))
BC_list.append({
'B': B,
'C': C
})
BC_list.sort(reverse=True, key=lambda x: x['C'])
A_last = min(A)
limit_count = 0
for pair in BC_list:
if pair['C'] < A_last:
break
for _ in range(pair['B']):
A.append(pair['C'])
limit_count += pair['B']
if limit_count > N:
break
A.sort(reverse=True)
print((sum(A[0:N])))
| p03038 |
from collections import deque
n,m=list(map(int,input().split()))
A=sorted(list(map(int,input().split())))
BC=sorted([list(map(int,input().split())) for i in range(m)],key=lambda x:x[1])
A=deque(A)
for b,c in BC[::-1]:
if len(A)==0:break
for i in range(b):
if A[0]<c:
A.append(c)
A.popleft()
else:break
print((sum(A))) | from collections import deque
n,m=list(map(int,input().split()))
A=sorted(list(map(int,input().split())))
BC=sorted([list(map(int,input().split())) for i in range(m)],key=lambda x:x[1])
A=deque(A)
for b,c in BC[::-1]:
for i in range(b):
if A[0]<c:
A.append(c)
A.popleft()
else:break
print((sum(A))) | p03038 |
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
BC = [[c]*b for b, c in [list(map(int, input().split())) for _ in range(M)]]
R=sum(BC,[])
T=sorted(A+R,reverse=True)
print((sum(T[:len(A)])))
| N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
BC = [[c]*b for b, c in [list(map(int, input().split())) for _ in range(M)]]
R=sum(BC,[])
if len(R)>len(A):
R=sorted(R,reverse=True)[:len(A)]
T=sorted(A+R,reverse=True)
print((sum(T[:len(A)])))
| p03038 |
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
BC = [[c]*b for b, c in [list(map(int, input().split())) for _ in range(M)]]
R=sum(BC,[])
if len(R)>len(A):
R=sorted(R,reverse=True)[:len(A)]
T=sorted(A+R,reverse=True)
print((sum(T[:len(A)])))
| N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
BC = [list(map(int, input().split())) for _ in range(M)]
BC.sort(key=lambda x:x[1],reverse=True)
R=[]
n=0
for i in BC:
R = R+[i[1]]*i[0]
n = n + i[0]
if n >= N:
break
R=sorted(A+R, reverse=True)[:N]
print((sum(R)))
| p03038 |
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
BC = [list(map(int, input().split())) for _ in range(M)]
BC.sort(key=lambda x:x[1],reverse=True)
R=[]
n=0
for i in BC:
R = R+[i[1]]*i[0]
n = n + i[0]
if n >= N:
break
R=sorted(A+R, reverse=True)[:N]
print((sum(R)))
| N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
BC = [list(map(int, input().split())) for _ in range(M)]
A.sort(reverse=True)
BC.sort(key=lambda x:x[1],reverse=True)
R=[]
n=0
for i in range(M):
R.extend([BC[i][1]]*BC[i][0])
n = n + BC[i][0]
if n >= N:
break
R=sorted(A+R, reverse=True)[:N]
print((sum(R)))
| p03038 |
n, m = tuple(map(int, input().split()))
x = sorted(list(map(int, input().split())))
y = [tuple(map(int, input().split())) for i in range(m)]
for b,c in y:
while x[b-1] > c and b > 0:
b -= 1
x[0:b] = [c]*b
x.sort()
print((sum(x))) | n, m = tuple(map(int, input().split()))
x = sorted(list(map(int, input().split())))
y = [list(map(int, input().split())) for i in range(m)]
y.sort(key = lambda x: x[1], reverse=True)
y_pos = 0
for index, value in enumerate(x):
b = y[y_pos][0]
c = y[y_pos][1]
if value < c:
x[index] = c
y[y_pos][0] = b-1
if b == 1:
y_pos += 1
if y_pos == len(y):
break
else:
break
print((sum(x)))
| p03038 |
n,m=list(map(int,input().split()))
*a,=list(map(int,input().split()))
l=[list(map(int,input().split()))[::-1] for _ in range(m)]
a.sort()
d=[]
e=0
for c,b in sorted(l)[::-1]:
d+=[c]*b
e+=b
if e>n:break
for i,(x,y) in enumerate(zip(a,d)):
if x<y:a[i]=y
print((sum(a)))
| n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
Z=[list(map(int,input().split()))[::-1] for _ in range(m)]
d=[]
e=0
a.sort()
Z.sort(reverse=True)
for c,b in Z:
d+=[c]*b
e+=b
if e>n:
break
for i , (x,y) in enumerate(zip(a,d)):
if x<y:
a[i]=y
print((sum(a)))
| p03038 |
import heapq
import sys
input = sys.stdin.readline
def main():
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
heapq.heapify(A)
for _ in range(M):
b, c = list(map(int, input().split()))
for _ in range(b):
n = heapq.heappop(A)
if n<c:
heapq.heappush(A, c)
else:
heapq.heappush(A, n)
break
print((sum(A)))
if __name__ == '__main__':
main() | import heapq
import sys
input = sys.stdin.readline
def main():
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
heapq.heapify(A)
BC = []
for _ in range(M):
b, c = list(map(int, input().split()))
BC.append([c*(-1), b])
heapq.heapify(BC)
flg = True
while flg:
if len(BC)==0:
break
c, b = heapq.heappop(BC)
c *= -1
for _ in range(b):
a = heapq.heappop(A)
if a<c:
heapq.heappush(A, c)
else:
heapq.heappush(A, a)
flg = False
break
print((sum(A)))
if __name__ == '__main__':
main()
| p03038 |
import heapq
N, M = list(map(int, input().split()))
A_LIST = list(map(int, input().split()))
BC_LIST = []
heapq.heapify(A_LIST)
for i in range(M):
b, c = list(map(int, input().split()))
BC_LIST.append([b, c])
BC_LIST.sort(reverse=True, key=lambda x: x[1]) # C降順にソート
for b, c in BC_LIST:
for _ in range(b):
tmp = heapq.heappop(A_LIST)
if tmp < c:
heapq.heappush(A_LIST, c)
else:
heapq.heappush(A_LIST, tmp)
break
print((sum(A_LIST)))
| N, M = list(map(int, input().split()))
A_LIST = list(map(int, input().split()))
BC_LIST = []
for i in range(M):
b, c = list(map(int, input().split()))
BC_LIST.append([b, c])
card_dict = {}
for a in A_LIST:
if a in card_dict:
card_dict[a] += 1
else:
card_dict[a] = 1
for b, c in BC_LIST:
if c in card_dict:
card_dict[c] += b
else:
card_dict[c] = b
card_list = sorted(list(card_dict.items()), reverse=True, key=lambda x: x[0])
ans = 0
remaining = N
for num, cnt in card_list:
ans += num * min(cnt, remaining)
remaining -= min(cnt, remaining)
if remaining == 0:
break
print(ans)
| p03038 |
import heapq
n,m=list(map(int,input().split()))
a=sorted(list(map(int, input().split())))
bc=[list(map(int, input().split())) for _ in range(m)]
bc.sort(key=lambda x:x[1])
heapq.heapify(a)
for b,c in bc:
for j in range(b):
amin=heapq.heappop(a)
if amin<c:
heapq.heappush(a,c)
else:
heapq.heappush(a,amin)
break
print((sum(a))) | def main():
import heapq
n,m=list(map(int,input().split()))
a=sorted(list(map(int, input().split())))
bc=[list(map(int, input().split())) for _ in range(m)]
bc.sort(key=lambda x:-x[1])
heapq.heapify(a)
for b,c in bc:
for j in range(b):
amin=heapq.heappop(a)
if amin<c:
heapq.heappush(a,c)
else:
heapq.heappush(a,amin)
break
print((sum(a)))
main() | p03038 |
import heapq
n, m = list(map(int, input().split()))
cards = list(map(int, input().split()))
heapq.heapify(cards)
queries = []
for i in range(m):
q = list(map(int, input().split()))
queries.append(q)
for q in queries:
b, c = q
cnt = 0
while cnt < b:
heapq.heappushpop(cards, c)
cnt += 1
ans = 0
for i in range(n):
ans += cards[i]
print(ans)
| import heapq
n, m = list(map(int, input().split()))
cards = list(map(int, input().split()))
cards.sort()
queries = []
for i in range(m):
q = list(map(int, input().split()))
queries.append(q)
queries.sort(key=lambda x: x[1])
queries.reverse()
ans = 0
pos = 0
for q in queries:
b, c = q
if cards[min(pos+b-1, n-1)] < c:
# print('a')
pos = pos + b
ans += c * (b - max(0, pos-n))
if pos >= n:
break
else:
for i in range(b):
if cards[pos+i] < c:
# print('b')
ans += c
else:
# print('c')
pos += i
for j in range(pos, n):
ans += cards[j]
pos = n
break
break
if pos < n:
for j in range(pos, n):
ans += cards[j]
print(ans)
| p03038 |
def s0():return eval(input())
def s1():return input().split()
def s2(n):return [eval(input()) for x in range(n)]
def s3(n):return [input().split() for _ in range(n)]
def s4(n):return [[x for x in s] for s in s2(n)]
def n0():return int(eval(input()))
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(eval(input())) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print((yes if b else no))
# from sys import setrecursionlimit
# setrecursionlimit(1000000)
# from collections import Counter,deque,defaultdict
# import itertools
# import math
# import networkx as nx
# from bisect import bisect_left,bisect_right
from heapq import heapify,heappush,heappop
n,m=n1()
A=n1()
BC=t3(m)
heapify(A)
# BC.sort(key=lambda x:x[1])
for b,c in BC:
for _ in range(b):
a=heappop(A)
if a>=c:
heappush(A,a)
break;
else:
heappush(A,c)
print((sum(A))) |
def s0():return eval(input())
def s1():return input().split()
def s2(n):return [eval(input()) for x in range(n)]
def s3(n):return [input().split() for _ in range(n)]
def s4(n):return [[x for x in s] for s in s2(n)]
def n0():return int(eval(input()))
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(eval(input())) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print((yes if b else no))
# from sys import setrecursionlimit
# setrecursionlimit(1000000)
# from collections import Counter,deque,defaultdict
# import itertools
# import math
# import networkx as nx
# from bisect import bisect_left,bisect_right
from heapq import heapify,heappush,heappop
n,m=n1()
A=n1()
BC=t3(m)
heapify(A)
BC.sort(key=lambda x:-x[1])
D=[]
for b,c in BC:
D.extend([c]*b)
if len(D)>=n:
break
D=D[:n]
for d in D:
a=heappop(A)
if a>=d:
heappush(A,a)
break;
else:
heappush(A,d)
print((sum(A))) | p03038 |
def binary_search(cards,n,number):
low=0
high=len(cards)-1
while high-low>1:
mid=(low+high)//2
base=cards[mid]
if base==number:
for i in range(n):
cards.insert(mid,number)
return cards,mid
if base<number:
low=mid
else:
high=mid
if cards[high]==cards[low]:
if number>cards[high]:
for i in range(n):
cards.insert(high+1, number)
else:
for i in range(n):
cards.insert(low, number)
else:
for i in range(n):
cards.insert(high,number)
return cards,mid
#1 3 5 7 9 11 <=8
#1 3 [5] 7 9 11 <= 8
#1 3 (5) 7 9 (11) <=8
#1 3 5 [7] 9 11 <= 8
#1 3 5 (7) 9 (11) <= 8
#1 3 5 7 [9] 11 <= 8
#1 3 5 (7) (9) 11
#1 3 5 [7] 9 11 <=8
#1 3 5 (7)
import sys
from heapq import heappush,heappop
def main():
inp1=list([int(x) for x in input().split()])
cards=list([int(x) for x in input().split()])
cards_heap=[]
for i in cards:
heappush(cards_heap,i)
N=inp1[0]
M=inp1[1]
B=[]
C=[]
for i in range(M):
changes=list([int(x) for x in input().split()])
B.append(changes[0])
C.append(changes[1])
cb=list(zip(C,B))
cb=sorted(cb,reverse=True)
C,B=list(zip(*cb))
hand=[]
for i in range(M):
hand.extend([C[i] for j in range(B[i])])
for i in hand:
a=heappop(cards_heap)
if i>a:
heappush(cards_heap,i)
else:
heappush(cards_heap,a)
break
print((sum(cards_heap)))
if __name__=="__main__":
main() | from heapq import heappush,heappop
def main():
inp1=list([int(x) for x in input().split()])
cards=list([int(x) for x in input().split()])
cards_heap=[]
for i in cards:
heappush(cards_heap,i)
N=inp1[0]
M=inp1[1]
B=[]
C=[]
for i in range(M):
changes=list([int(x) for x in input().split()])
B.append(changes[0])
C.append(changes[1])
cb=list(zip(C,B))
cb=sorted(cb,reverse=True)
for C,B in cb:
for _ in range(B):
a=heappop(cards_heap)
if C>a:
heappush(cards_heap,C)
else:
heappush(cards_heap,a)
break
print((sum(cards_heap)))
if __name__=="__main__":
main() | p03038 |
from bisect import bisect
n, m = list(map(int, input().split()))
*a, = list(map(int, input().split()))
a.sort()
BC = []
for _ in range(m):
b, c = list(map(int, input().split()))
BC.append((b, c))
BC = sorted(BC, key=lambda x: x[1], reverse=True)
ans = 0
num = 0
for b, c in BC:
idx = bisect(a[num:], c)
p = min(idx, b)
num += p
ans += c * p
print((sum(a[num:])+ans))
| n, m = list(map(int, input().split()))
a = [(1, int(i)) for i in input().split()]
for _ in range(m):
b, c = list(map(int, input().split()))
a.append((b, c))
a = sorted(a, key=lambda x: x[1])
ans = 0
t = 0
while t < n:
b, c = a.pop()
p = min(b, n-t)
ans += p * c
t += p
print(ans)
| p03038 |
import bisect
N, M = list(map(int, input().split()))
*a, = list(map(int, input().split()))
BC = []
for _ in range(M):
b, c = list(map(int, input().split()))
BC.append((b, c))
a.sort()
BC = sorted(BC, key=lambda x: x[1], reverse=True)
ans = 0
for b, c in BC:
idx = bisect.bisect_right(a, c)
if b <= idx:
ans += b * c
a = a[b:]
else:
ans += idx * c
a = a[idx:]
ans += sum(a)
print(ans)
| N, M = list(map(int, input().split()))
a = [(1, int(i)) for i in input().split()]
for _ in range(M):
b, c = list(map(int, input().split()))
a.append((b, c))
a = sorted(a, key=lambda x: x[1])
ans = 0
t = 0
while t < N:
b, c = a.pop()
p = min(b, N-t)
ans += p * c
t += p
print(ans)
| p03038 |
import heapq
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
heapq.heapify(A)
CB = []
for i in range(M):
b, c = list(map(int, input().split()))
CB.append([c, b])
CB.sort()
D = []
for c, b in CB:
D += [c]*b
for i in range(N):
if D:
d = D.pop()
g = heapq.heappushpop(A, d)
if d == g:
break
else:
break
print((sum(A))) | N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
CB = []
for i in range(M):
b, c = list(map(int, input().split()))
CB.append([c, b])
D = [[a, 1] for a in A] + CB
D.sort()
ans = 0
while N > 0:
c, b = D.pop()
ans += min(N, b)*c
N -= b
print(ans) | p03038 |
from operator import itemgetter
N,M = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
A.sort()
BC = [[int(x) for x in input().split()]for _ in range(M)]
BC.sort(key = itemgetter(1),reverse=True)
x = 0
for i in BC:
y = 0
while(x+y<len(A) and y<i[0]):
if(A[x+y]<i[1]):
A[x+y]=i[1]
y += 1
else:
x += 1
x = y
print((sum(A)))
| from operator import itemgetter
import sys
sys.setrecursionlimit(1000000)
N,M = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
A.sort()
BC = [[int(x) for x in input().split()]for _ in range(M)]
BC.sort(key = itemgetter(1),reverse=True)
x = 0
bc_ind = 0
ans = 0
for ind,i in enumerate(A):
bc = 0
if(BC[bc_ind][0]>x):
bc = BC[bc_ind][1]
x+=1
else:
bc_ind+=1
x = 1
if(len(BC)<=bc_ind):
ans += sum(A[ind:])
break
else:
bc = BC[bc_ind][1]
if(bc>i):
ans += bc
else:
ans += sum(A[ind:])
break
print(ans)
| p03038 |
#!/usr/bin/env python3
N, M = list(map(int, input().rstrip().split()))
A = list(map(int, input().rstrip().split()))
B = []
C = []
for _ in range(M):
b, c = list(map(int, input().rstrip().split()))
B.append(b)
C.append(c)
Index = sorted(list(range(M)), key=lambda i: C[i], reverse=True)
sum = 0
for index in Index:
A.sort()
count = 0
i = 0
while True:
if i >= len(A):
break
if A[i] < C[index] and count < B[index]:
sum += C[index]
A.pop(i)
# print(A)
count += 1
continue
if A[i] >= C[index] or count >= B[index]:
break
i += 1
if A:
for a in A:
sum += a
print(sum)
| #!/usr/bin/env python3
N, M = list(map(int, input().rstrip().split()))
A = list(map(int, input().rstrip().split()))
B = []
C = []
for _ in range(M):
b, c = list(map(int, input().rstrip().split()))
B.append(b)
C.append(c)
Index = sorted(list(range(M)), key=lambda i: C[i], reverse=True)
sum = 0
A.sort()
for index in Index:
count = 0
i = 0
while True:
if i >= len(A):
break
if A[i] < C[index] and count < B[index]:
sum += C[index]
A.pop(i)
# print(A)
count += 1
continue
if A[i] >= C[index] or count >= B[index]:
break
i += 1
if A:
for a in A:
sum += a
print(sum)
| p03038 |
#!/usr/bin/env python3
N, M = list(map(int, input().rstrip().split()))
A = list(map(int, input().rstrip().split()))
B = []
C = []
for _ in range(M):
b, c = list(map(int, input().rstrip().split()))
B.append(b)
C.append(c)
Index = sorted(list(range(M)), key=lambda i: C[i], reverse=True)
sum = 0
A.sort()
for index in Index:
count = 0
i = 0
while True:
if i >= len(A):
break
if A[i] < C[index] and count < B[index]:
sum += C[index]
A.pop(i)
# print(A)
count += 1
continue
if A[i] >= C[index] or count >= B[index]:
break
i += 1
if A:
for a in A:
sum += a
print(sum)
| #!/usr/bin/env python3
N, M = list(map(int, input().rstrip().split()))
A = list(map(int, input().rstrip().split()))
B = []
C = []
for _ in range(M):
b, c = list(map(int, input().rstrip().split()))
B.append(b)
C.append(c)
Index = sorted(list(range(M)), key=lambda i: C[i], reverse=True)
sum = 0
A.sort()
for index in Index:
if A and A[0] >= C[index]:
break
count = 0
i = 0
while True:
if i >= len(A):
break
if A[i] < C[index] and count < B[index]:
sum += C[index]
A.pop(i)
# print(A)
count += 1
continue
if A[i] >= C[index] or count >= B[index]:
break
i += 1
if A:
for a in A:
sum += a
print(sum)
| p03038 |
import math
import fractions
import copy
#以下てんぷら
def j(q):
if q==1: print("YES")
elif q == 0:print("NO")
exit(0)
rem = pow(10,9)+7
"""
def ct(x,y):
if (x>y):print("+")
elif (x<y): print("-")
else: print("?")
"""
def ip():
return int(eval(input()))
def printrow(a):
for i in a:
print(i)
def combinations(n,r):
if n<r:return 0
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def permutations(n,r):
if n<r:return 0
return math.factorial(n) // math.factorial(n - r)
def lcm(x, y):
return (x * y) // fractions.gcd(x, y)
#n = ip() #入力整数1つ
n,m= (int(i) for i in input().split()) #入力整数横2つ以上
a = [int(i) for i in input().split()] #入力整数配列
#a = input() #入力文字列
#a = input().split() #入力文字配列
#n = ip() #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(n)] #入力セット(整数改行あり)(2/2)
#a=[input() for i in range(n)] #入力セット(整数改行あり)(2/2)
#jの変数はしようできないので注意
#全足しにsum変数使用はsum関数使用できないので注意
b = []
for i in range(m):
x,y = (int(i) for i in input().split())
b.append([y,x])
b.sort(reverse=True)
a.sort()
s = 0
while (len(a)):
if a[0] < b[0][0]:
a.pop(0)
s+=b[0][0]
b[0][1]-=1
if b[0][1] == 0:
b.pop(0)
if b == []:
s += sum(a)
break
else:
b.pop(0)
if b == []:
s+=sum(a)
break
print(s) | import math
import fractions
import copy
#以下てんぷら
def j(q):
if q==1: print("YES")
elif q == 0:print("NO")
exit(0)
rem = pow(10,9)+7
"""
def ct(x,y):
if (x>y):print("+")
elif (x<y): print("-")
else: print("?")
"""
def ip():
return int(eval(input()))
def printrow(a):
for i in a:
print(i)
def combinations(n,r):
if n<r:return 0
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def permutations(n,r):
if n<r:return 0
return math.factorial(n) // math.factorial(n - r)
def lcm(x, y):
return (x * y) // fractions.gcd(x, y)
#n = ip() #入力整数1つ
n,m= (int(i) for i in input().split()) #入力整数横2つ以上
a = [int(i) for i in input().split()] #入力整数配列
#a = input() #入力文字列
#a = input().split() #入力文字配列
#n = ip() #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(n)] #入力セット(整数改行あり)(2/2)
#a=[input() for i in range(n)] #入力セット(整数改行あり)(2/2)
#jの変数はしようできないので注意
#全足しにsum変数使用はsum関数使用できないので注意
b = []
for i in range(m):
x,y = (int(i) for i in input().split())
b.append([y,x])
b.sort(reverse=True)
a.sort()
s = 0
pa = 0
pb = 0
while (pa < len(a)):
if a[pa] < b[pb][0]:
pa+=1
s+=b[pb][0]
b[pb][1]-=1
if b[pb][1] == 0:
pb+=1
if len(b) == pb:
s += sum(a[pa:])
break
else:
pb+=1
if len(b) == pb:
s+=sum(a[pa:])
break
print(s) | p03038 |
N, M = [int(i) for i in input().strip().split()]
A = [int(i) for i in input().strip().split()]
A.sort()
for i in range(M):
B, C = [int(i) for i in input().strip().split()]
is_changed = False
for j in range(0, B):
if A[j] < C:
A[j] = C
is_changed = True
else:
break
if is_changed:
A.sort()
print((sum(A)))
| N, M = [int(i) for i in input().strip().split()]
A = [int(i) for i in input().strip().split()]
A.sort()
BC = [[0, 0] for _ in range(M)]
for j in range(M):
BC[j][0], BC[j][1] = [int(i) for i in input().strip().split()]
BC.sort(key=lambda x: x[1])
res = 0
cnt = 0
i = N - 1
j = M - 1
while True:
if cnt == N:
break
if j == -1:
res += A[i]
i -= 1
elif A[i] > BC[j][1]:
res += A[i]
i -= 1
elif A[i] <= BC[j][1]:
res += BC[j][1]
BC[j][0] -= 1
if BC[j][0] == 0:
j -= 1
else:
raise ValueError
cnt += 1
print(res)
| p03038 |
from heapq import heapify, heappop, heappush
def solve():
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
heapify(A)
for _ in range(M):
B, C = list(map(int, input().split()))
for _ in range(B):
if A[0] < C:
heappop(A)
heappush(A, C)
else:
break
print((sum(A)))
if __name__ == '__main__':
solve() | from operator import itemgetter
def solve():
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
BC = [[] for _ in range(M)]
for i in range(M):
BC[i] = list(map(int, input().split()))
BC.sort(key=itemgetter(1), reverse=True)
change = []
for b, c in BC:
change += [c for _ in range(b)]
if N < len(change):
break
A += change
A.sort()
ans = sum(A[-N:])
print(ans)
if __name__ == '__main__':
solve() | p03038 |
N,M=list(map(int,input().split()))
A=list(map(int,input().split()))
import heapq
heapq.heapify(A)
for i in range(M):
b,c=list(map(int,input().split()))
for j in range(b):
val=heapq.heappop(A)
if val<c:
heapq.heappush(A,c)
else:
heapq.heappush(A,val)
break
print((sum(A))) | N,M=list(map(int,input().split()))
A=list(map(int,input().split()))
Q=[None]*M
for i in range(M):
b,c=list(map(int,input().split()))
Q[i]=[b,c]
Q=sorted(Q,key=lambda x:x[1])[::-1]
A=sorted(A)
ind=0
for i in range(len(Q)):
b,c=Q[i]
for p in range(b):
if ind+p>=len(A):
print((sum(A)))
exit(0)
if A[ind+p]<c:
A[ind+p]=c
else:
break
ind+=b
else:
print((sum(A))) | p03038 |
#import math
#import copy
#import sys
#import bisect
#input = sys.stdin.readline
mod=10**9+7
def swap(a,b):
c=a
a=b
b=c
return a,b
def factorial(x): #階乗計算
n=1
for i in range(x):
n=(n*(i+1))%mod
return n
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a%b)
def lcm(a, b):
return((a*b)//gcd(a,b))
def div(x): #約数配列
div=[1]
check=2
while(x!=1 and check <= int(x**0.5)+2):
if(x%check==0):
div.append(check)
while(x%check==0):
x=x//check
check+=1
if x != 1:
div.append(x)
return div
def div2(x): #素因数分解配列
div2=[]
check=2
while(x!=1 and check <= int(x**0.5)+2):
while x%check==0:
div2.append(check)
x/=check
check+=1
if x != 1:
div2.append(x)
return div2
def main():
# x,y = map(int,input().split()) x=1,y=2
# a = input().split() a=['1','2','3',...,'n']
# a = list(map(int,input().split())) a=[1,2,3,4,5,...,n]
# li = input().split('T') FFFTFTTFF => li=['FFF', 'F', '', 'FF']
# 複数行の「1 2 3 4」型の入力を一配列に
# x = sorted([list(map(int, input().split())) for _ in range(n)])
# ソート x.sort(key=lambda y:y[1])
# [chr(i) for i in range(97, 97+26)] 英語小文字リスト
# [chr(i) for i in range(65, 65+26)] 英語大文字リスト atcoder
# ord(c) chr(2) alphabet <=> number
n,m = list(map(int,input().split()))
a = list(map(int,input().split()))
bc=sorted([list(map(int, input().split())) for _ in range(m)])
bc.sort(key=lambda x:x[1],reverse=True)
tank=[]
i=0
while len(tank)<n and bc[i][1]>min(a):
for _ in range(bc[i][0]):
tank.append(bc[i][1])
if len(tank)==n:
break
i+=1
if i==m:
break
a+=tank
a.sort(reverse=True)
print((sum(a[:n])))
main() | #import math
#import copy
#import sys
#import bisect
#input = sys.stdin.readline
mod=10**9+7
def swap(a,b):
c=a
a=b
b=c
return a,b
def factorial(x): #階乗計算
n=1
for i in range(x):
n=(n*(i+1))%mod
return n
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a%b)
def lcm(a, b):
return((a*b)//gcd(a,b))
def div(x): #約数配列
div=[1]
check=2
while(x!=1 and check <= int(x**0.5)+2):
if(x%check==0):
div.append(check)
while(x%check==0):
x=x//check
check+=1
if x != 1:
div.append(x)
return div
def div2(x): #素因数分解配列
div2=[]
check=2
while(x!=1 and check <= int(x**0.5)+2):
while x%check==0:
div2.append(check)
x/=check
check+=1
if x != 1:
div2.append(x)
return div2
def main():
# x,y = map(int,input().split()) x=1,y=2
# a = input().split() a=['1','2','3',...,'n']
# a = list(map(int,input().split())) a=[1,2,3,4,5,...,n]
# li = input().split('T') FFFTFTTFF => li=['FFF', 'F', '', 'FF']
# 複数行の「1 2 3 4」型の入力を一配列に
# x = sorted([list(map(int, input().split())) for _ in range(n)])
# ソート x.sort(key=lambda y:y[1])
# [chr(i) for i in range(97, 97+26)] 英語小文字リスト
# [chr(i) for i in range(65, 65+26)] 英語大文字リスト atcoder
# ord(c) chr(2) alphabet <=> number
n,m = list(map(int,input().split()))
a = list(map(int,input().split()))
bc=sorted([list(map(int, input().split())) for _ in range(m)])
bc.sort(key=lambda x:x[1],reverse=True)
a.sort()
i=j=0
while bc[i][1]>a[j]:
for _ in range(bc[i][0]):
if bc[i][1]<=a[j]:
break
a[j]=bc[i][1]
j+=1
if j==n:
break
i+=1
if i==m or j==n or bc[i][1]<=a[j]:
break
print((sum(a)))
main() | p03038 |
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
L = []
for i in range(M):
b, c = list(map(int, input().split()))
_ = [c, b]
L.append(_)
L.sort()
L.reverse()
c = 0
D = []
while c < N and len(L) > 0:
for i in range(L[0][1]):
D.append(L[0][0])
c += 1
del L[0]
i = 0
while D[i] >= A[i] and i < N and i < len(D):
i += 1
if i == len(D) or i == N:
break
x = sum(D[:i]) + sum(A[i:])
print(x) | N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
L = []
for i in range(M):
b, c = list(map(int, input().split()))
L.append((c, b))
L = sorted(L, reverse = True)
L.append((0, N))
temp = 0
sum = 0
for i in range(M + 1):
for j in range(L[i][1]):
if A[temp] < L[i][0]:
sum += L[i][0]
temp += 1
else:
sum += A[temp]
temp += 1
if temp == N:
break
if temp == N:
break
print(sum) | p03038 |
n, m = list(map(int, input().split(' ')))
aaa = list(map(int, input().split(' ')))
r = 100000
cccbbb = []
for i in range(m):
b, c = list(map(int, input().split(' ')))
cccbbb += [c] * b
aaa = sorted(aaa)
cccbbb = sorted(cccbbb)[::-1]
len_cccbbb = len(cccbbb)
len_aaa = len(aaa)
#print(aaa)
#print(cccbbb)
if len_aaa < len_cccbbb:
#print(([max(a, c) for a, c in zip(aaa, cccbbb[:len_aaa])]))
print((sum([max(a, c) for a, c in zip(aaa, cccbbb[:len_aaa])])))
elif len_aaa >= len_cccbbb:
#print(([max(a, c) for a, c in zip(aaa, cccbbb + [0] * (len_aaa - len_cccbbb))]))
print((sum([max(a, c) for a, c in zip(aaa, cccbbb + [0] * (len_aaa - len_cccbbb))])))
| n, m = list(map(int, input().split(' ')))
aaa = list(map(int, input().split(' ')))
aaa = sorted(aaa)
len_aaa = len(aaa)
cccbbb = []
for i in range(m):
b, c = list(map(int, input().split(' ')))
cccbbb += [c] * b
cccbbb = sorted(cccbbb)[::-1]
if len(cccbbb) > len(aaa):
cccbbb = cccbbb[:len_aaa]
len_cccbbb = len(cccbbb)
if len_aaa < len_cccbbb:
print((sum([max(a, c) for a, c in zip(aaa, cccbbb[:len_aaa])])))
elif len_aaa >= len_cccbbb:
print((sum([max(a, c) for a, c in zip(aaa, cccbbb + [0] * (len_aaa - len_cccbbb))])))
| p03038 |
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
opes = [tuple(map(int, input().split())) for _ in range(M)]
D = [C for B, C in opes for _ in range(B)]
D = sorted(D, reverse=True)[:N]
A.sort()
for i, d in enumerate(D):
if A[i] >= d:
break
A[i] = d
print((sum(A)))
| N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
opes = [tuple(map(int, input().split())) for _ in range(M)]
opes.sort(key=lambda x:-x[1])
D = []
lenD = 0
for B, C in opes:
D += [C]*B
lenD += B
if lenD >= N:
break
A.sort()
for i, d in enumerate(D[:N]):
if A[i] >= d:
break
A[i] = d
print((sum(A)))
| p03038 |
# coding:utf-8
import math
import re
def main(params):
n,m = params[0]
a = params[1]
tmpA = []
for i in a:
i = int(i)
tmpA.append(i)
a = tmpA
a.sort()
a.reverse()
r = []
for g in params[2:]:
b = int(g.split()[0])
c = int(g.split()[1])
t = [c] * b
r.extend(t)
r.sort()
r.reverse()
cnt = 0
total = 0
while True:
if len(a) == 0:
total += r[0]
r.pop(0)
elif len(r) == 0:
total += a[0]
a.pop(0)
elif a[0] < r[0]:
total += r[0]
r.pop(0)
else:
total += a[0]
a.pop(0)
cnt += 1
if cnt == n:
break
print(total)
# a = params[1].split()
# b = list(params[2])
if __name__ == "__main__":
n,m = input().split()
n = int(n)
m = int(m)
a = input().split()
cnt = m # TODO: edit here
params = [[n,m],a]
for i in range(cnt):
param = input()
params.append(param)
main(params)
| # coding:utf-8
import math
import re
def main(params):
n,m = params[0]
a = params[1]
tmpA = []
for i in a:
i = int(i)
tmpA.append(i)
a = tmpA
a.sort()
a.reverse()
r = {}
for g in params[2:]:
b = int(g.split()[0])
c = int(g.split()[1])
if c not in r:
r[c] = b
else:
r[c] += b
# t = [c] * b
# r.extend(t)
# r.sort()
# r.reverse()
rV = list(r.keys())
rV.sort()
rV.reverse()
cnt = 0
total = 0
while True:
if len(a) == 0:
total += rV[0]
r[rV[0]] -= 1
if r[rV[0]] == 0:
rV.pop(0)
elif len(rV) == 0:
total += a[0]
a.pop(0)
elif a[0] < rV[0]:
total += rV[0]
r[rV[0]] -= 1
if r[rV[0]] == 0:
rV.pop(0)
else:
total += a[0]
a.pop(0)
cnt += 1
if cnt == n:
break
print(total)
# a = params[1].split()
# b = list(params[2])
if __name__ == "__main__":
n,m = input().split()
n = int(n)
m = int(m)
a = input().split()
cnt = m # TODO: edit here
params = [[n,m],a]
for i in range(cnt):
param = input()
params.append(param)
main(params)
| p03038 |
from heapq import heapify, heappush, heappop
import sys
input = sys.stdin.readline
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
a = heapify(A)
B = [0] * M
C = [0] * M
for i in range(M):
B[i], C[i] = list(map(int, input().split()))
cb = sorted(zip(C, B), reverse=True)
for c, b in cb:
for _ in range(b):
m = heappop(A)
heappush(A, max(m, c))
if m > c:
break
print((sum(A))) | from heapq import heapify, heappush, heappop
import sys
input = sys.stdin.readline
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
B = [0] * M
C = [0] * M
for i in range(M):
B[i], C[i] = list(map(int, input().split()))
cb = sorted(zip(C, B), reverse=True)
cnt = 0
exchange = []
for c, b in cb:
exchange.extend([c] * b)
cnt += b
if cnt >= N:
break
exchange.sort()
for _ in range(len(exchange)):
m = heappop(A)
heappush(A, max(m, exchange.pop()))
print((sum(A))) | p03038 |
from heapq import heapify, heappush, heappop
import sys
input = sys.stdin.readline
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
B = [0] * M
C = [0] * M
for i in range(M):
B[i], C[i] = list(map(int, input().split()))
cb = sorted(zip(C, B), reverse=True)
cnt = 0
exchange = []
for c, b in cb:
exchange.extend([c] * b)
cnt += b
if cnt >= N:
break
exchange.sort()
for _ in range(len(exchange)):
m = heappop(A)
heappush(A, max(m, exchange.pop()))
print((sum(A))) | import sys
input = sys.stdin.readline
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
B = [0] * M
C = [0] * M
for i in range(M):
B[i], C[i] = list(map(int, input().split()))
cb = sorted(zip(C, B), reverse=True)
exchange = []
for c, b in cb:
exchange.extend([c] * b)
if len(exchange) >= N:
break
A.extend(exchange)
A.sort(reverse=True)
print((sum(A[:N]))) | p03038 |
import bisect
N,M = list(map(int,input().split()))
A = list(map(int,input().split()))
BC = [list(map(int,input().split())) for _ in range(M)]
for b,c in BC:
A += [c] * b
# print(A)
# print(sorted(A))
# print(sorted(A)[-N:])
print((sum(sorted(A)[-N:]))) |
N,M = list(map(int,input().split()))
A = list(map(int,input().split()))
BC = [list(map(int,input().split())) for _ in range(M)]
for b,c in BC:
A += [c] * b
# print(A)
# print(sorted(A))
# print(sorted(A)[-N:])
print((sum(sorted(A)[-N:]))) | p03038 |
import sys
from collections import deque
readline = sys.stdin.readline
n, m = list(map(int, readline().split()))
a = sorted(list(map(int, readline().split())))
bc = []
for _ in range(m):
b, c = list(map(int, readline().split()))
for _ in range(b):
bc.append(c)
bc.sort(key=lambda x: -x)
dbc = deque(bc)
for i in range(n):
if len(dbc) > 0 and a[i] < dbc[0]:
a[i] = dbc.popleft()
print((sum(a))) | import sys
from collections import deque
readline = sys.stdin.readline
n, m = list(map(int, readline().split()))
a = sorted(list(map(int, readline().split())))
bc = []
for _ in range(m):
b, c = list(map(int, readline().split()))
bc.append([b * c, c])
bc.sort(key=lambda x: -x[1])
dbc = deque(bc)
for i in range(n):
if len(dbc) > 0 and a[i] < dbc[0][1]:
a[i] = dbc[0][1]
dbc[0][0] -= dbc[0][1]
if dbc[0][0] == 0:
dbc.popleft()
print((sum(a))) | p03038 |
#!/usr/bin/env python3
import sys
INF = float("inf")
def solve(N: int, M: int, A: "List[int]", B: "List[int]", C: "List[int]"):
A.sort() # 昇順 O(NlongN)
BC = list(zip(B, C))
BC.sort(key=lambda x: x[1], reverse=True) # 降順 MlogM
Cs = []
for b, c in BC: # M
Cs.extend([c]*b)
s = 0
for i, (a, c) in enumerate(zip(A, Cs)):
if a >= c:
s += a
break
s += max(a, c)
if i < len(A)-1:
for j in range(i+1, len(A)):
s += A[j]
print(s)
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
M = int(next(tokens)) # type: int
A = [int(next(tokens)) for _ in range(N)] # type: "List[int]"
B = [int()] * (M) # type: "List[int]"
C = [int()] * (M) # type: "List[int]"
for i in range(M):
B[i] = int(next(tokens))
C[i] = int(next(tokens))
solve(N, M, A, B, C)
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
import sys
INF = float("inf")
def solve(N: int, M: int, A: "List[int]", B: "List[int]", C: "List[int]"):
A.sort() # 昇順 O(NlongN)
BC = list(zip(B, C))
BC.sort(key=lambda x: x[1], reverse=True) # 降順 MlogM
Cs = []
for b, c in BC: # M
Cs.extend([c]*b)
s = 0
for i, (a, c) in enumerate(zip(A, Cs)): # N
if a >= c:
s += a
break
s += max(a, c)
if i < len(A)-1:
for j in range(i+1, len(A)):
s += A[j]
print(s)
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
M = int(next(tokens)) # type: int
A = [int(next(tokens)) for _ in range(N)] # type: "List[int]"
B = [int()] * (M) # type: "List[int]"
C = [int()] * (M) # type: "List[int]"
for i in range(M):
B[i] = int(next(tokens))
C[i] = int(next(tokens))
solve(N, M, A, B, C)
if __name__ == '__main__':
main()
| p03038 |
import bisect
import sys
input = sys.stdin.readline
from collections import deque
def solve():
n,m = (int(i) for i in input().split())
a = list(int(i) for i in input().split())
a.sort()
tmp = deque([])
for i in range(m):
r,l = (int(i) for i in input().split())
tmp.append((l,r))
tmp= deque(sorted(tmp,reverse =True))
ans = 0
while tmp:
c,b = tmp.popleft()
place = bisect.bisect_left(a,c)-1
if place == -1:
break
else:
if len(a) == 0:
break
a = a[min(1+place,b)::]
ans += c*(min(1+place,b))
#print(a)
if a:
ans += sum(a)
print (ans)
solve() | import bisect
import sys
input = sys.stdin.readline
from collections import deque
def solve():
n,m = (int(i) for i in input().split())
a = list(int(i) for i in input().split())
a = deque(sorted(a))
tmp = deque([])
for i in range(m):
r,l = (int(i) for i in input().split())
tmp.append((l,r))
tmp= deque(sorted(tmp,reverse =True))
ans = 0
while tmp:
c,b = tmp.popleft()
place = bisect.bisect_left(a,c)-1
if place == -1:
break
else:
if len(a) == 0:
break
for i in range(min(1+place,b)):
a.popleft()
ans += c*(min(1+place,b))
#print(a)
if a:
ans += sum(a)
print (ans)
solve() | p03038 |
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
input = sys.stdin.readline
# bisect_left(lists, 3)
# bisect_right(lists, 3)
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除&その最小値を出力
# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと
def main():
N, M = list(map(int, input().split(" ")))
#N = int(input())
#S = input()
A = input().split(" ")
A = list(A)
#A = A[:-1]
A = [int(s) * (-1) for s in A]
heapq.heapify(A)
for i in range(M):
b, c = list(map(int, input().split(" ")))
for _ in range(b):
heapq.heappush(A, c * (-1))
ans = 0
for i in range(N):
tmp = heapq.heappop(A) * (-1)
ans += tmp
#print(tmp)
print(ans)
if __name__ == "__main__":
main() | # -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
input = sys.stdin.readline
# bisect_left(lists, 3)
# bisect_right(lists, 3)
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除&その最小値を出力
# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと
def main():
N, M = list(map(int, input().split(" ")))
#N = int(input())
#S = input()
A = input().split(" ")
A = list(A)
#A = A[:-1]
A = [(int(s) * (-1), 1) for s in A]
heapq.heapify(A)
for i in range(M):
b, c = list(map(int, input().split(" ")))
heapq.heappush(A, (c * (-1), b))
ans = []
for i in range(N):
t, con = heapq.heappop(A)
for _ in range(con):
if len(ans) == N:
print((sum(ans)))
sys.exit()
ans.append(t * (-1))
print((sum(ans)))
if __name__ == "__main__":
main() | p03038 |
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
from bisect import bisect_left
n, m = list(map(int, input().split()))
a = list( map(int, input().split()))
a.sort()
bc = [tuple(map(int,input().split())) for i in range(m)]
bc = sorted(bc, reverse=True, key=lambda x: x[1])
cnt = 0
for b, c in bc:
index = bisect_left(a[cnt:], c)+cnt
tmp = min(index,b+cnt)
for i in range(cnt,tmp):
a[i] = c
cnt = tmp
print((sum(a)))
| import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
from bisect import bisect_left
n, m = list(map(int, input().split()))
a = list( map(int, input().split()))
a.sort()
bc = [tuple(map(int,input().split())) for i in range(m)]
bc = sorted(bc, reverse=True, key=lambda x: x[1])
i = 0
for b, c in bc:
for _ in range(b):
if c <= a[i]: break
a[i] = c
i += 1
if i >= n :break
else:
continue
break
print((sum(a))) | p03038 |
def d_integer_cards(N, M, A, Operation_info):
from bisect import bisect_left
from collections import deque
a = deque(sorted(A))
Operation_info.sort(key=lambda x: x[1], reverse=True)
tmp = []
for b, c in Operation_info:
index = bisect_left(a, c)
if index > 0:
for j in range(min(b, index)):
a.popleft()
tmp.append(c)
return sum(list(a) + tmp)
N, M = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
Operation_info = [[int(i) for i in input().split()] for j in range(M)]
print((d_integer_cards(N, M, A, Operation_info))) | def d_integer_cards(N, M, A, Operation_info):
# Aの要素は1回選ぶことができるとみなす
# 値C_iはB_i回選ぶことができるとみなす
selected_num = [[1, a] for a in A] + Operation_info
selected_num.sort(key=lambda x: x[1], reverse=True)
# 値yをx回選ぶことを、選んだ値の個数がNになるまで繰り返す
select = 0
ans = 0
for x, y in selected_num:
select += x
ans += x * y
if select >= N:
ans -= (select - N) * y
break
return ans
N, M = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
Operation_info = [[int(i) for i in input().split()] for j in range(M)]
print((d_integer_cards(N, M, A, Operation_info))) | p03038 |
from collections import deque
N, M = list(map(int, input().split(" ")))
A = list(map(int, input().split(" ")))
A_que = deque(A)
for i in range(M):
B, C = list(map(int, input().split(" ")))
for j in range(B):
A_que.append(C)
A = list(A_que)
A.sort(reverse=True)
print((sum(A[0:N]))) | N, M = list(map(int, input().split(" ")))
A = list(map(int, input().split(" ")))
A.sort()
D = []
for i in range(M):
B, C = list(map(int, input().split(" ")))
D.append((C, B))
#D = list(D_dict)
D.sort(reverse=True)
D_index = 0
D_index_max = len(D)
ans = 0
ct_D_i = 0
ct_D_i_max = D[0][1]
ct_D_total = 0
for i in range(N):
a = A[i]
d = D[D_index][0]
if a > d:
break
A[i] = d
ct_D_i += 1
if ct_D_i >= ct_D_i_max:
D_index += 1
if D_index >= D_index_max:
break
ct_D_i = 0
ct_D_i_max = D[D_index][1]
print((sum(A))) | p03038 |
from collections import deque
n,m=list(map(int,input().split()))
a=deque(list(map(int,input().split())))
#a=deque(a)
for i in range(m):
b,c=list(map(int,input().split()))
l=[c for _ in range(b)]
a.extend(l)
a=list(a)
#print(a)
a.sort(reverse=1)
a=a[:n]
print((sum(a)))
#print(a) | from collections import deque
n,m=list(map(int,input().split()))
a=deque(list(map(int,input().split())))
bc=[list(map(int,input().split())) for _ in range(m)]
bc.sort(key=lambda x: x[1])
bc=bc[::-1]
l=0
for b,c in bc:
if l>n:
break
else:
d=[c]*b
a.extend(d)
l+=b
a=list(a)
#print(a)
a.sort(reverse=1)
a=a[:n]
print((sum(a)))
#print(a) | p03038 |
ni = lambda: int(eval(input()))
nm = lambda: list(map(int, input().split()))
nl = lambda: list(map(int, input().split()))
n, m = nm()
a = nl()
for i in range(m):
b, c = nm()
a += [c] * b
print((sum(sorted(a, reverse=True)[:n]))) | ni = lambda: int(eval(input()))
nm = lambda: list(map(int, input().split()))
nl = lambda: list(map(int, input().split()))
n, m = nm()
a = sorted(nl())
pos = 0
changer = []
for i in range(m):
b, c = nm()
changer.append((c, b))
changer = sorted(changer)[::-1]
for i in range(m):
c = changer[i]
for j in range(c[1]):
while pos < n:
if a[pos] < c[0]:
a[pos] = c[0]
break
pos += 1
if pos >= n:
break
print((sum(a)))
| p03038 |
import sys
from collections import deque
from copy import copy
from bisect import bisect_right, bisect_left
N,M = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
BC=[]
for m in range(M):
b,c = list(map(int, input().split()))
BC.append([b,c])
BC.sort(key=lambda bc: bc[1], reverse=True)
_sum = 0
for b,c in BC:
i = bisect_left(A, c)
if i == 0:
break
nrof_replace = min(i,b)
_sum += c * nrof_replace
A = A[nrof_replace:]
print((_sum + sum(A)))
| import sys
from collections import deque
from copy import copy
from bisect import bisect_right, bisect_left
N,M = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
A = deque(A)
BC=[]
for m in range(M):
b,c = list(map(int, input().split()))
BC.append([b,c])
BC.sort(key=lambda bc: bc[1], reverse=True)
_sum = 0
for b,c in BC:
i = bisect_left(A, c)
if i == 0:
break
nrof_replace = min(i,b)
_sum += c * nrof_replace
#A = A[nrof_replace:]
for i in range(nrof_replace):
A.popleft()
print((_sum + sum(A)))
| p03038 |
from collections import defaultdict
n,m=list(map(int,input().split()))
A=[int(i) for i in input().split()]
A.sort()
D=defaultdict(int)
for i in range(m):
b,c=list(map(int,input().split()))
D[c]+=b
D=sorted(list(D.items()),key=lambda x:x[0],reverse=True)
DD=[0]*n
ct=0
for x,y in D:
for i in range(y):
if i+ct<n:
DD[i+ct]+=x
ct+=y
ans=0
for i in range(n):
ans+=max(A[i],DD[i])
print(ans)
| from collections import defaultdict
from collections import Counter
n,m=list(map(int,input().split()))
A=[int(i) for i in input().split()]
AA=dict(Counter(A))
D=defaultdict(int)
for i in range(m):
b,c=list(map(int,input().split()))
D[c]+=b
for x in list(AA.keys()):
D[x]+=AA[x]
D=sorted(list(D.items()),key=lambda x:x[0],reverse=True)
ans,tot=0,0
for x,y in D:
if tot+y<=n:
ans+=x*y
tot+=y
else:
ans+=x*(n-tot)
tot+=n-tot
if tot==n:
break
print(ans) | p03038 |
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
for i in range(M):
B, C = list(map(int, input().split()))
A = A + [C,]*B
A.sort(reverse=True)
sum = 0
for i in range(N):
sum = sum + A[i]
print(sum) | N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
Nd = {}
for i in range(M):
B, C = list(map(int, input().split()))
if C in list(Nd.keys()):
Nd[C] = Nd[C] + B
else:
Nd[C] = B
for a in A:
if a in list(Nd.keys()):
Nd[a] = Nd[a] + 1
else:
Nd[a] = 1
Nd = sorted(list(Nd.items()), key=lambda x: -x[0]) # type=list
sum = 0
for key, val in Nd:
if N >= val:
sum = sum + key*val
N = N-val
else:
sum = sum + key*N
break;
print(sum) | p03038 |
# ABC127 D-Integer Cards
from operator import itemgetter
N,M = list(map(int,input().split()))
A = list(map(int,input().split()))
BC = [list(map(int, input().split())) for _ in range(M)]
BC.sort(key=itemgetter(1),reverse=True)
# print(A)
# print('sort',BC)
for i in range(M):
x = 0
while x < BC[i][0]:
A.sort()
# print(i,A)
if BC[i][1] > A[0]:
A[0] = BC[i][1]
x += 1
print((sum(A))) | # ABC127 D-Integer Cards
from operator import itemgetter
N,M = list(map(int,input().split()))
A = list(map(int,input().split()))
BC = [list(map(int, input().split())) for _ in range(M)]
A.sort()
BC.sort(key=itemgetter(1),reverse=True)
# print(A)
# print('sort',BC)
c = 0
for i in range(M):
for j in range(BC[i][0]):
if A[c] < BC[i][1]:
A[c] = BC[i][1]
else:
print((sum(A)))
exit()
c += 1
if c == N:
print((sum(A)))
exit()
# for i in range(M):
# x = 0
# while x < BC[i][0]:
# A.sort()
# print(i,A)
# if BC[i][1] > A[0]:
# A[0] = BC[i][1]
# x += 1
print((sum(A))) | p03038 |
# ABC127 D-Integer Cards
from operator import itemgetter
N,M = list(map(int,input().split()))
A = list(map(int,input().split()))
BC = [list(map(int, input().split())) for _ in range(M)]
A.sort()
BC.sort(key=itemgetter(1),reverse=True)
# print(A)
# print('sort',BC)
c = 0
for i in range(M):
for j in range(BC[i][0]):
if A[c] < BC[i][1]:
A[c] = BC[i][1]
else:
print((sum(A)))
exit()
c += 1
if c == N:
print((sum(A)))
exit()
# for i in range(M):
# x = 0
# while x < BC[i][0]:
# A.sort()
# print(i,A)
# if BC[i][1] > A[0]:
# A[0] = BC[i][1]
# x += 1
print((sum(A))) | # ABC127 D-Integer Cards
from operator import itemgetter
N,M = list(map(int,input().split()))
A = list(map(int,input().split()))
BC = [list(map(int, input().split())) for _ in range(M)]
A.sort()
BC.sort(key=itemgetter(1),reverse=True)
c = 0
for i in range(M):
for j in range(BC[i][0]):
if A[c] < BC[i][1]:
A[c] = BC[i][1]
else:
print((sum(A)))
exit()
c += 1
if c == N:
print((sum(A)))
exit()
print((sum(A))) | p03038 |
n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
b=[]
for i in range(m):
bb,cc=list(map(int,input().split()))
b.append([cc,bb])
a.sort()
b.sort(reverse=True)
i=0
j=0
while i<n:
if j==m:
break
if b[j][1]>0:
if a[i]<b[j][0]:
a[i]=b[j][0]
b[j][1]-=1
i+=1
elif a[i]>=b[j][0]:
break
else:
j+=1
print((sum(a))) | n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
bc=[list(map(int,input().split())) for i in range(m)]
a.sort()
bc.sort(key=lambda x: x[1],reverse=True)
# print(a)
# print(bc)
i=0
for b,c in bc:
tb=b
while tb>0:
if n==i:
break
if a[i]>=c:
break
a[i]=c
tb-=1
i+=1
if n==i:break
if a[i]>=c :
break
print((sum(a))) | p03038 |
import heapq
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
change = []
for m in range(M):
B, C = list(map(int, input().split()))
change.append((B, C))
change.sort(key=lambda x: -x[1])
change2 = []
for c in change:
change2.extend([c[1]] * c[0])
if len(change2) >= N:
change2 = change2[:N]
break
heapq.heapify(A)
for c in change2:
x = heapq.heappop(A)
if x >= c:
# 先頭すでに十分大きい場合は抜ける
heapq.heappush(A, x)
break
else:
x = max(x, c)
heapq.heappush(A, x)
print((sum(A)))
| import heapq
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
# 交換できるカードを大きい順にリスト化する
exchange1 = []
for m in range(M):
B, C = list(map(int, input().split()))
exchange1.append((B, C))
exchange1.sort(key=lambda x: -x[1])
exchange2 = []
for c in exchange1:
exchange2.extend([c[1]] * c[0])
# 手持ちのカード枚数を超えたら抜ける
if len(exchange2) >= N:
exchange2 = exchange2[:N]
break
heapq.heapify(A)
for c in exchange2:
x = heapq.heappop(A)
if x >= c:
# 先頭すでに十分大きい場合は抜ける
heapq.heappush(A, x)
break
else:
x = max(x, c)
heapq.heappush(A, x)
print((sum(A)))
| p03038 |
import sys
import heapq
n,m=list(map(int,sys.stdin.readline().split()))
a=list(map(int,sys.stdin.readline().split()))
a.sort
for i in range(m):
b,c=list(map(int,sys.stdin.readline().split()))
t=[c]*b
a=list(heapq.merge(a,t))
print((sum(heapq.nlargest(n,a)))) | n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
bc=[list(map(int,input().split())) for i in range(m)]
bc.sort(key=lambda x:x[1],reverse=True)
for b,c in bc:
a.extend([c]*b)
if len(a)>2*n:
break
a.sort(reverse=True)
print((sum(a[:n]))) | p03038 |
N, M = list(map(int, input().split()))
A = sorted([int(i) for i in input().split()])
B = []
for _ in range(M):
b, c = list(map(int, input().split()))
B += [c] * b
B.sort(reverse = True)
x = min(N, len(B))
for i in range(x):
A[i] = max(A[i], B[i])
print((sum(A))) | N, M = list(map(int, input().split()))
A = sorted([int(i) for i in input().split()])
C = sorted([[int(i) for i in input().split()] for i in range(M)], reverse = True,
key = lambda x: x[1])
cnt = 0
B = []
for i in range(M):
if cnt > N:
break
B += [C[i][1]] * C[i][0]
cnt += C[i][0]
B.sort(reverse = True)
x = min(N, len(B))
for i in range(x):
A[i] = max(A[i], B[i])
print((sum(A))) | p03038 |
s=input().split()
n=int(s[0])
m=int(s[1])
s=input().split()
l=list(map(int, s))
for i in range(m):
s=input().split()
l.extend([int(s[1])]*int(s[0]))
l.sort()
print((sum(l[-n:])))
| s=input().split()
n=int(s[0])
m=int(s[1])
s=input().split()
l=list(map(int, s))
num=min(l)
for i in range(m):
s=input().split()
a=int(s[1])
if a>num:
l.extend([a]*int(s[0]))
l.sort()
print((sum(l[-n:])))
| p03038 |
import heapq
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
heapq.heapify(a)
b = []
for i in range(m):
u, v = list(map(int, input().split()))
for j in range(u):
b.append(-v)
heapq.heapify(b)
while len(b) > 0:
x = heapq.heappop(a)
y = heapq.heappop(b)
if x < -y:
heapq.heappush(a, -y)
else:
heapq.heappush(a, x)
break
print((sum(a))) | import heapq
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
heapq.heapify(a)
for i in range(m):
u, v = list(map(int, input().split()))
for j in range(u):
if v > a[0]:
heapq.heappushpop(a, v)
print((sum(a))) | p03038 |
N,M=list(map(int,input().split()))
A=list(map(int,input().split()))
tmp,count,l0=A[0],1,[]
for i in range(1,N):
if tmp==A[i]:
count+=1
else:
l0.append([tmp,count])
tmp=A[i]
count=1
l0.append([tmp,count])
BC=[]
for i in range(M):
BC.append(list(map(int,input().split())))
BC.sort(key=lambda x:x[1],reverse=True)
cnt=0
l1=[]
for b,c in BC:
if cnt>N:
break
else:
l1.append([c,b])
cnt+=b
l=l0+l1
l.sort(key=lambda x:x[0],reverse=True)
d=0
ans=0
while d<N:
if l[0][1]==0:
l.remove(l[0])
ans+=l[0][0]
d+=1
l[0][1]-=1
print(ans) | N,M=list(map(int,input().split()))
A=list(map(int,input().split()))
BC=[]
for i in range(M):
BC.append(list(map(int,input().split())))
A.sort(reverse=True)
BC.sort(key=lambda x:x[1],reverse=True)
ans=sum(A)
for i in range(M):
for _ in range(BC[i][0]):
if A==[]:
print(ans)
exit()
if A[-1]>BC[i][1]:
print(ans)
exit()
else:
p=A.pop()
ans-=p
ans+=BC[i][1]
print(ans) | p03038 |
def main():
import sys
input = sys.stdin.readline
from bisect import bisect_left,bisect
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
S = [list(map(int, input().split())) for i in range(M)]
A.sort()
A = A[::-1]
S = sorted(S, key=lambda x: x[1])[::-1]
T = []
count = 0
for i in range(M):
T += [S[i][1]]*S[i][0]
count += S[i][0]
a = 0
t = 0
SUM = 0
for _ in range(N):
if t >= count:
SUM += A[a]
a += 1
elif A[a] > T[t]:
SUM += A[a]
a += 1
else:
SUM += T[t]
t += 1
print(SUM)
main() | def main():
import sys
input = sys.stdin.readline
from bisect import bisect_left,bisect
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
S = [list(map(int, input().split())) for i in range(M)]
A.sort()
A = A[::-1]
S = sorted(S, key=lambda x: x[1])[::-1]
T = []
count = 0
for i in range(M):
T += [S[i][1]]*S[i][0]
count += S[i][0]
if count >= N:
break
a = 0
t = 0
SUM = 0
for _ in range(N):
if t >= count:
SUM += A[a]
a += 1
elif A[a] > T[t]:
SUM += A[a]
a += 1
else:
SUM += T[t]
t += 1
print(SUM)
main() | p03038 |
import bisect
N, M = list(map(int, input().split()))
A = sorted(list(map(int, input().split())))
ans = sum(A)
for _ in range(M):
b, c = list(map(int, input().split()))
if c <= A[0]:
continue
index = bisect.bisect_left(A, c)
index = min(index, b)
for i in range(index):
ans += c - A[i]
A[i] = c
if index > 0:
A = sorted(A)
print(ans)
| N, M = list(map(int, input().split()))
A = sorted(list(map(int, input().split())))
bc = [list(map(int, input().split())) for _ in range(M)]
ans = sum(A)
bc = sorted(bc, key=lambda i: i[1], reverse=True)
i = 0
for b, c in bc:
for _ in range(b):
if A[i] > c:
break
ans += c - A[i]
i += 1
if i >= N:
break
else:
continue
break
print(ans) | p03038 |
import sys
input = sys.stdin.readline
def main():
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
count = 0
add = []
mini = 0
cb = [None]*m
for i in range(m):
b, c = list(map(int, input().split()))
cb[i] = (c, b)
cb.sort(reverse=True)
for c, b in cb:
count += b
add += [c]*b
if count >= n:
mini = c
break
add = add[:n] # 追加のカードを削るかどうか
a.sort() # 昇順
idx = len(a)//2
for _ in range(10):
if a[idx] <= mini: # aの中央がminiより小さい
a = a[idx:]
idx = len(a)//2
else:
idx //= 2
new_a = a + add
new_a.sort(reverse=True)
print((sum(new_a[:n])))
if __name__ == '__main__':
main()
| import sys
input = sys.stdin.readline
def main():
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
cb = [None]*m
for i in range(m):
b, c = list(map(int, input().split()))
cb[i] = (c, b)
cb.sort(reverse=True)
add = []
count = 0
for c, b in cb:
add += [c]*b
count += b
if count >= n:
break
a += add
a.sort(reverse=True)
print((sum(a[:n])))
if __name__ == '__main__':
main()
| p03038 |
import heapq
N, M = list(map(int, input().split()))
A = list([int(x) for x in input().split()])
heapq.heapify(A)
for i in range(M):
b, c = list(map(int, input().split()))
for j in range(b):
d = heapq.heappushpop(A, c)
if c == d:
break
print((sum(A))) | N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
exc = []
for i in range(M):
exc.append(list(map(int, input().split())))
exc.sort(key=lambda x: x[1], reverse=True)
e = []
count = 0
for i in range(M):
e += [exc[i][1]] * exc[i][0]
count += exc[i][0]
if count >= N:
break
cards = sorted(A+e, reverse=True)
print((sum(cards[:N])))
| p03038 |
from collections import Counter
n, m = list(map(int, input().split()))
a = Counter(list(map(int, input().split())))
bc = [list(map(int, input().split())) for i in range(m)]
b = {}
ans = 0
for i, j in bc:
if j in b:
ref = b[j]
b[j] = ref + i
else:
b[j] = i
d = Counter(a) + Counter(b)
keys = sorted(d)[::-1]
for key in keys:
qty = d[key]
if qty < n:
ans += qty*key
n -= qty
else:
ans += n*key
break
print(ans) | n, m = list(map(int, input().split()))
l = [(a, 1) for a in list(map(int, input().split()))]
for i in range(m):
b, c = list(map(int, input().split()))
l.append((c, b))
l = sorted(l)[::-1]
ans = 0
for i, j in l:
if j < n:
ans += i*j
n -= j
else:
ans += n*i
break
print(ans) | p03038 |
from heapq import heappushpop, heapify
n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
heapify(a)
gomi=a[0]
bc=[]
for _ in range(m):
b,c=list(map(int,input().split()))
bc.append((c,b))
bc.sort(reverse=True)
for i in bc:
c,b=i
if gomi>c:
break
for i in range(b):
heappushpop(a, c)
gomi=a[0]
print((sum(a))) | import heapq
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
heapq.heapify(a)
CB=[]
for _ in range(m):
b, c = list(map(int, input().split()))
CB.append((c, b))
CB.sort(reverse=True)
for c, b in CB:
if a[0] >= c:
break
for _ in range(b):
if a[0] >= c:
break
heapq.heappushpop(a, c)
print((sum(a))) | p03038 |
N, M = list(map(int, input().split()))
A = sorted(list(map(int, input().split())))
L = [tuple(map(int, input().split())) for _ in range(M)]
L.sort(key=lambda x: x[1], reverse=True)
flag = True
num = 0
while flag:
if num >= M:
break
for i in range(L[num][0]):
if L[num][1] > A[0]:
A[0] = L[num][1]
A.sort()
else:
flag = False
break
num += 1
print((sum(A)))
| N, M = list(map(int, input().split()))
A = sorted(list(map(int, input().split())))
L = [tuple(map(int, input().split())) for _ in range(M)]
L.sort(key=lambda x: x[1], reverse=True)
flag = True
num = 0
now = 0
while flag:
if num >= M:
break
for i in range(L[num][0]):
if now < N and L[num][1] > A[now]:
A[now] = L[num][1]
now += 1
else:
flag = False
break
num += 1
print((sum(A)))
| p03038 |
N,M=list(map(int,input().split()))
A=list(map(int,input().split()))
B=[]
for m in range(M):
b,c=list(map(int,input().split()))
B+=[c]*b
A=sorted(A)
B=sorted(B)[::-1]
Max=0
for i in range(N+1):
New=sum(A[i:])+sum(B[:i])
if New>Max:
Max=New
print(Max) | def main(A,B,N):
A=sorted(A)
B=sorted(B)[::-1]
K=len(B)
R=min(N,K)
for i in range(R):
if A[i]>B[i]:
return sum(B[:i]+A[i:])
return sum(B[:R]+A[R:])
N,M=list(map(int,input().split()))
A=list(map(int,input().split()))
B=[]
for m in range(M):
b,c=list(map(int,input().split()))
B+=[c]*b
print((main(A,B,N))) | p03038 |
def main(A,D,N):
K=min(N,len(D))
for i in range(K):
if A[i]>D[i]:
return sum(D[:i]+A[i:])
return sum(D[:K]+A[K:])
N,M=list(map(int,input().split()))
A=list(map(int,input().split()))
A.sort()
CB=[]
for m in range(M):
b,c=list(map(int,input().split()))
CB.append([c,b])
CB.sort()
CB.reverse()
D=[]
while len(D)<N and CB!=[]:
D.append(CB[0][0])
CB[0][1]-=1
if CB[0][1]==0:
CB.remove(CB[0])
for cb in CB:
D+=[cb[0]]*cb[1]
print((main(A,D,N))) | N,M=list(map(int,input().split()))
A=list(map(int,input().split()))
BC=[]
for m in range(M):
b,c=list(map(int,input().split()))
BC.append([b,c])
A.sort()
BC.sort(key=lambda x:x[1],reverse=True)
D=[]
for [b,c] in BC:
D+=[c]*b
if len(D)>N:
break
if len(D)<N:
D+=[0]*(N-len(D))
AD=[max(A[i],D[i]) for i in range(N)]
print((sum(AD))) | p03038 |
import bisect
import sys
sys.setrecursionlimit(10**9)
def mi(): return list(map(int,input().split()))
def ii(): return int(eval(input()))
def isp(): return input().split()
def deb(text): print(("-------\n{}\n-------".format(text)))
class Counter:
def __init__(self):
self.dict = {}
def add(self,x):
if x in self.dict: self.dict[x] += 1
else: self.dict[x] = 1
def decrement(self,x):
self.dict[x] -= 1
if self.dict[x] <= 0:
del self.dict[x]
def get_dict(self):
return self.dict
INF=10**20
def main():
N,M=mi()
A=list(mi())
X = []
counter = Counter()
for a in A:
counter.add(a)
# count = counter.get_dict()
# for a,count in count_dic.items():
# X.append((a,count))
# X.sort()
keys = list(counter.get_dict().keys()) # カードの数字
keys.sort()
# print(counter.get_dict())
for i in range(M):
b,c = mi()
j = bisect.bisect_left(keys,c)
rest = b
for k in range(j+1):
if not 0<=k<len(keys): continue
key = keys[k]
if key >= c: continue
count = counter.get_dict()[key]
if count < rest:
counter.get_dict()[key] = 0
rest -= count
counter.add(c)
counter.get_dict()[c] += -1 + count
else:
counter.get_dict()[key] = count - rest
counter.add(c)
counter.get_dict()[c] += -1 + rest
rest = 0
if rest == 0:
break
# if key < c:
# counter.decrement(key)
# counter.add(c)
keys = list(counter.get_dict().keys())
keys.sort()
# print(counter.get_dict())
ans = 0
for a, count in list(counter.get_dict().items()):
# print(a,count)
ans += a * count
print(ans)
if __name__ == "__main__":
main() | import sys
sys.setrecursionlimit(10**9)
def mi(): return list(map(int,input().split()))
def ii(): return int(eval(input()))
def isp(): return input().split()
def deb(text): print(("-------\n{}\n-------".format(text)))
class Counter:
def __init__(self):
self.dict = {}
def add(self,x):
if x in self.dict: self.dict[x] += 1
else: self.dict[x] = 1
def decrement(self,x):
self.dict[x] -= 1
if self.dict[x] <= 0:
del self.dict[x]
def get_dict(self):
return self.dict
INF=10**20
def main():
N,M=mi()
A=list(mi())
X = []
for i in range(M):
b,c=mi()
X.append((c,b))
X.sort(reverse=True)
A.sort(reverse=True)
xi = 0
b = 0
newA = []
while A:
if not xi < len(X): break
if b == 0: c,b = X[xi]
a = A.pop() # 小さい順に
# print(a,b,c)
if a < c:
newA.append(c)
else:
A.append(a)
b = 0
b -= 1
if b <= 0:
xi += 1
# print(A)
# print(newA)
print((sum(newA) + sum(A)))
if __name__ == "__main__":
main() | p03038 |
import heapq
class mcf_graph_int_cost:
"""
costが整数の時の高速化。
"""
def __init__(self, n):
self.n = n
self.log = (n.bit_length() + 7) // 8 * 8
self.mask = (1 << self.log) - 1
self.pos = []
self.g = [[] for _ in range(n)]
def add_edge(self, from_, to, cap, cost):
assert 0 <= from_ < self.n
assert 0 <= to < self.n
m = len(self.pos)
self.pos.append((from_, len(self.g[from_])))
self.g[from_].append(self.__class__._edge(to, len(self.g[to]), cap, cost))
self.g[to].append(self.__class__._edge(from_, len(self.g[from_]) - 1, 0, -cost))
return m
class edge:
def __init__(self, from_, to, cap, flow, cost):
self.from_ = from_
self.to = to
self.cap = cap
self.flow = flow
self.cost = cost
def get_edge(self, i):
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
return self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)
def edges(self):
ret = []
for i in range(len(self.pos)):
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
ret.append(self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost))
return ret
def slope(self, s, t, flow_limit=float('inf')):
# assert 0 <= s < self.n
# assert 0 <= t < self.n
# assert s != t
dual = [0] * self.n
dist = [float('inf')] * self.n
pv = [-1] * self.n
pe = [-1] * self.n
vis = [False] * self.n
def _dual_ref():
nonlocal dual, dist, pv, pe, vis
dist = [float('inf')] * self.n
pv = [-1] * self.n
pe = [-1] * self.n
vis = [False] * self.n
que = [s]
dist[s] = 0
while que:
v = heapq.heappop(que) & self.mask
if vis[v]:
continue
vis[v] = True
if v == t:
break
for i in range(len(self.g[v])):
e = self.g[v][i]
if vis[e.to] or e.cap == 0:
continue
cost = e.cost - dual[e.to] + dual[v]
if dist[e.to] > dist[v] + cost:
dist[e.to] = dist[v] + cost
pv[e.to] = v
pe[e.to] = i
heapq.heappush(que, ((dist[e.to] << self.log) + e.to))
if not vis[t]:
return False
for v in range(self.n):
if not vis[v]:
continue
dual[v] -= dist[t] - dist[v]
return True
flow = 0
cost = 0
prev_cost = -1
result = [(flow, cost)]
while flow < flow_limit:
if not _dual_ref():
break
c = flow_limit - flow
v = t
while v != s:
c = min(c, self.g[pv[v]][pe[v]].cap)
v = pv[v]
v = t
while v != s:
e = self.g[pv[v]][pe[v]]
e.cap -= c
self.g[v][e.rev].cap += c
v = pv[v]
d = -dual[s]
flow += c
cost += c * d
if prev_cost == d:
result.pop()
result.append((flow, cost))
prev_cost = cost
return result
def flow(self, s, t, flow_limit=float('inf')):
return self.slope(s, t, flow_limit)[-1]
class _edge:
def __init__(self, to, rev, cap, cost):
self.to = to
self.rev = rev
self.cap = cap
self.cost = cost
BIG = 10 ** 9
import sys
input = sys.stdin.readline
N, K = list(map(int, input().split()))
g = mcf_graph_int_cost(2 * N + 2)
s = 2 * N
t = 2 * N + 1
g.add_edge(s, t, N * K, BIG)
for i in range(N):
g.add_edge(s, i, K, 0)
g.add_edge(N + i, t, K, 0)
for i in range(N):
As = list(map(int, input().split()))
for j, A in enumerate(As):
g.add_edge(i, N + j, 1, BIG - A)
result = g.flow(s, t, N * K)
print((N * K * BIG - result[1]))
grid = [['.' for _ in range(N)] for _ in range(N)]
edges = g.edges()
for e in edges:
if e.from_ == s or e.to == t or e.flow == 0:
continue
grid[e.from_][e.to - N] = 'X'
for row in grid:
print((''.join(row))) | import heapq
class mcf_graph_int_cost:
"""
頂点数、及び、costの総和が、4294967295 (== (1 << 32) - 1) を超えない前提下での高速な実装。
後者は超えても一応動く。
"""
def __init__(self, n):
self.n = n
self.pos = []
self.g = [[] for _ in range(n)]
def add_edge(self, from_, to, cap, cost):
# assert 0 <= from_ < self.n
# assert 0 <= to < self.n
m = len(self.pos)
self.pos.append((from_, len(self.g[from_])))
self.g[from_].append(self.__class__._edge(to, len(self.g[to]), cap, cost))
self.g[to].append(self.__class__._edge(from_, len(self.g[from_]) - 1, 0, -cost))
return m
class edge:
def __init__(self, from_, to, cap, flow, cost):
self.from_ = from_
self.to = to
self.cap = cap
self.flow = flow
self.cost = cost
def get_edge(self, i):
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
return self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)
def edges(self):
ret = []
for i in range(len(self.pos)):
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
ret.append(self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost))
return ret
def slope(self, s, t, flow_limit=4294967295):
# assert 0 <= s < self.n
# assert 0 <= t < self.n
# assert s != t
dual = [0] * self.n
dist = [4294967295] * self.n
pv = [-1] * self.n
pe = [-1] * self.n
vis = [False] * self.n
def _dual_ref():
nonlocal dual, dist, pv, pe, vis
dist = [4294967295] * self.n
pv = [-1] * self.n
pe = [-1] * self.n
vis = [False] * self.n
que = [s]
dist[s] = 0
while que:
v = heapq.heappop(que) & 4294967295
if vis[v]:
continue
vis[v] = True
if v == t:
break
for i in range(len(self.g[v])):
e = self.g[v][i]
if vis[e.to] or e.cap == 0:
continue
cost = e.cost - dual[e.to] + dual[v]
if dist[e.to] > dist[v] + cost:
dist[e.to] = dist[v] + cost
pv[e.to] = v
pe[e.to] = i
heapq.heappush(que, ((dist[e.to] << 32) + e.to))
if not vis[t]:
return False
for v in range(self.n):
if not vis[v]:
continue
dual[v] -= dist[t] - dist[v]
return True
flow = 0
cost = 0
prev_cost = -1
result = [(flow, cost)]
while flow < flow_limit:
if not _dual_ref():
break
c = flow_limit - flow
v = t
while v != s:
c = min(c, self.g[pv[v]][pe[v]].cap)
v = pv[v]
v = t
while v != s:
e = self.g[pv[v]][pe[v]]
e.cap -= c
self.g[v][e.rev].cap += c
v = pv[v]
d = -dual[s]
flow += c
cost += c * d
if prev_cost == d:
result.pop()
result.append((flow, cost))
prev_cost = cost
return result
def flow(self, s, t, flow_limit=4294967295):
return self.slope(s, t, flow_limit)[-1]
class _edge:
def __init__(self, to, rev, cap, cost):
self.to = to
self.rev = rev
self.cap = cap
self.cost = cost
BIG = 10 ** 9
import sys
input = sys.stdin.readline
N, K = list(map(int, input().split()))
g = mcf_graph_int_cost(2 * N + 2)
s = 2 * N
t = 2 * N + 1
g.add_edge(s, t, N * K, BIG)
for i in range(N):
g.add_edge(s, i, K, 0)
g.add_edge(N + i, t, K, 0)
for i in range(N):
As = list(map(int, input().split()))
for j, A in enumerate(As):
g.add_edge(i, N + j, 1, BIG - A)
result = g.flow(s, t, N * K)
print((N * K * BIG - result[1]))
grid = [['.' for _ in range(N)] for _ in range(N)]
edges = g.edges()
for e in edges:
if e.from_ == s or e.to == t or e.flow == 0:
continue
grid[e.from_][e.to - N] = 'X'
for row in grid:
print((''.join(row))) | p02562 |
from heapq import heappop, heappush, heapify
class MinCostFlow():
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(n)]
self.pos = []
def add_edge(self, fr, to, cap, cost):
assert 0 <= fr < self.n
assert 0 <= to < self.n
m = len(self.pos)
self.pos.append((fr, len(self.graph[fr])))
self.graph[fr].append([to, len(self.graph[to]), cap, cost])
self.graph[to].append([fr, len(self.graph[fr]) - 1, 0, -cost])
return m
def get_edge(self, idx):
assert 0 <= idx < len(self.pos)
to, rev, cap, cost = self.graph[self.pos[idx][0]][self.pos[idx][1]]
rev_to, rev_rev, rev_cap, rev_cost = self.graph[to][rev]
return self.pos[idx][0], to, cap + rev_cap, rev_cap, cost
def edges(self):
for i in range(len(self.pos)):
yield self.get_edge(i)
def dual_ref(self, s, t):
dist = [2**63 - 1] * self.n
dist[s] = 0
vis = [0] * self.n
self.pv = [-1] * self.n
self.pe = [-1] * self.n
queue = []
heappush(queue, (0, s))
while queue:
k, v = heappop(queue)
if vis[v]: continue
vis[v] = True
if v == t: break
for i in range(len(self.graph[v])):
to, rev, cap, cost = self.graph[v][i]
if vis[to] or cap == 0: continue
cost += self.dual[v] - self.dual[to]
if dist[to] - dist[v] > cost:
dist[to] = dist[v] + cost
self.pv[to] = v
self.pe[to] = i
heappush(queue, (dist[to], to))
if not vis[t]: return False
for v in range(self.n):
if not vis[v]: continue
self.dual[v] -= dist[t] - dist[v]
return True
def flow(self, s, t):
return self.flow_with_limit(s, t, 2**63 - 1)
def flow_with_limit(self, s, t, limit):
return self.slope_with_limit(s, t, limit)[-1]
def slope(self, s, t):
return self.slope_with_limit(s, t, 2**63 - 1)
def slope_with_limit(self, s, t, limit):
assert 0 <= s < self.n
assert 0 <= t < self.n
assert s != t
flow = 0
cost = 0
prev_cost = -1
res = [(flow, cost)]
self.dual = [0] * self.n
while flow < limit:
if not self.dual_ref(s, t): break
c = limit - flow
v = t
while v != s:
c = min(c, self.graph[self.pv[v]][self.pe[v]][2])
v = self.pv[v]
v = t
while v != s:
to, rev, cap, _ = self.graph[self.pv[v]][self.pe[v]]
self.graph[self.pv[v]][self.pe[v]][2] -= c
self.graph[v][rev][2] += c
v = self.pv[v]
d = -self.dual[s]
flow += c
cost += c * d
if prev_cost == d:
res.pop()
res.append((flow, cost))
prev_cost = cost
return res
MAX = 10**9
N, K = list(map(int, input().split()))
A = [tuple(map(int, input().split())) for _ in range(N)]
mcf = MinCostFlow(2 * N + 2)
s = 2 * N
t = 2 * N + 1
mcf.add_edge(s, t, N * K, MAX)
for i in range(N):
mcf.add_edge(s, i, K, 0)
mcf.add_edge(i + N, t, K, 0)
for j in range(N):
mcf.add_edge(i, j + N, 1, MAX - A[i][j])
print((N * K * MAX - mcf.flow_with_limit(s, t, N * K)[1]))
res = [['.' for j in range(N)] for i in range(N)]
for fr, to, cap, flow, cost in mcf.edges():
if flow == 0 or fr == s or to == t:
continue
res[fr][to - N] = 'X'
for r in res:
print((''.join(r))) | from heapq import heappop, heappush, heapify
class MinCostFlow():
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(n)]
self.pos = []
def add_edge(self, fr, to, cap, cost):
#assert 0 <= fr < self.n
#assert 0 <= to < self.n
m = len(self.pos)
self.pos.append((fr, len(self.graph[fr])))
self.graph[fr].append([to, len(self.graph[to]), cap, cost])
self.graph[to].append([fr, len(self.graph[fr]) - 1, 0, -cost])
return m
def get_edge(self, idx):
#assert 0 <= idx < len(self.pos)
to, rev, cap, cost = self.graph[self.pos[idx][0]][self.pos[idx][1]]
rev_to, rev_rev, rev_cap, rev_cost = self.graph[to][rev]
return self.pos[idx][0], to, cap + rev_cap, rev_cap, cost
def edges(self):
for i in range(len(self.pos)):
yield self.get_edge(i)
def dual_ref(self, s, t):
dist = [2**63 - 1] * self.n
dist[s] = 0
vis = [0] * self.n
self.pv = [-1] * self.n
self.pe = [-1] * self.n
queue = []
heappush(queue, (0, s))
while queue:
k, v = heappop(queue)
if vis[v]: continue
vis[v] = True
if v == t: break
for i in range(len(self.graph[v])):
to, rev, cap, cost = self.graph[v][i]
if vis[to] or cap == 0: continue
cost += self.dual[v] - self.dual[to]
if dist[to] - dist[v] > cost:
dist[to] = dist[v] + cost
self.pv[to] = v
self.pe[to] = i
heappush(queue, (dist[to], to))
if not vis[t]: return False
for v in range(self.n):
if not vis[v]: continue
self.dual[v] -= dist[t] - dist[v]
return True
def flow(self, s, t):
return self.flow_with_limit(s, t, 2**63 - 1)
def flow_with_limit(self, s, t, limit):
return self.slope_with_limit(s, t, limit)[-1]
def slope(self, s, t):
return self.slope_with_limit(s, t, 2**63 - 1)
def slope_with_limit(self, s, t, limit):
#assert 0 <= s < self.n
#assert 0 <= t < self.n
#assert s != t
flow = 0
cost = 0
prev_cost = -1
res = [(flow, cost)]
self.dual = [0] * self.n
while flow < limit:
if not self.dual_ref(s, t): break
c = limit - flow
v = t
while v != s:
c = min(c, self.graph[self.pv[v]][self.pe[v]][2])
v = self.pv[v]
v = t
while v != s:
to, rev, cap, _ = self.graph[self.pv[v]][self.pe[v]]
self.graph[self.pv[v]][self.pe[v]][2] -= c
self.graph[v][rev][2] += c
v = self.pv[v]
d = -self.dual[s]
flow += c
cost += c * d
if prev_cost == d:
res.pop()
res.append((flow, cost))
prev_cost = cost
return res
MAX = 10**9
N, K = list(map(int, input().split()))
A = [tuple(map(int, input().split())) for _ in range(N)]
mcf = MinCostFlow(2 * N + 2)
s = 2 * N
t = 2 * N + 1
mcf.add_edge(s, t, N * K, MAX)
for i in range(N):
mcf.add_edge(s, i, K, 0)
mcf.add_edge(i + N, t, K, 0)
for j in range(N):
mcf.add_edge(i, j + N, 1, MAX - A[i][j])
print((N * K * MAX - mcf.flow_with_limit(s, t, N * K)[1]))
res = [['.' for j in range(N)] for i in range(N)]
for fr, to, cap, flow, cost in mcf.edges():
if flow == 0 or fr == s or to == t:
continue
res[fr][to - N] = 'X'
for r in res:
print((''.join(r))) | p02562 |
#-------最強ライブラリMinCostFlow(Python)------
#速度確認
import heapq
# numeric_limitsわかんね
NUMERIC_LIMITS = 10 ** 18
class mcf_graph:
pos = []
def __init__(s):
None
def __init__ (s, n):
s._n = n
s.g = [[] for _ in range(n)]
def add_edge(s, frm, to, cap, cost):
m = len(s.pos)
s.pos.append([frm, len(s.g[frm])])
s.g[frm].append(s._edge(to, len(s.g[to]), cap, cost))
s.g[to].append(s._edge(frm, len(s.g[frm]) - 1, 0, -cost))
return m
class edge:
def __init__(s, frm, to, cap, flow, cost):
s.frm, s.to = frm, to
s.cap, s.flow, s.cost = cap, flow, cost
def get_edge(s, i):
m = len(s.pos)
_e = s.g[s.pos[i][0]][s.pos[i][1]]
_re = s.g[_e.to][_e.rev]
return s.edge(s.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)
def edges(s):
return [s.get_edge(i) for i in range(len(s.pos))]
def flow(self, s, t):
return self.flow(s, t, NUMERIC_LIMITS)
def flow(self, s, t, flow_limit):
return self.slope(s, t, flow_limit)[-1]
def slope(self, s, t):
return self.slope(s, t, NUMERIC_LIMITS)
def slope(self, s, t, flow_limit):
#priority_queueの代わり
push = heapq.heappush
pop = heapq.heappop
dual, dist = [0] * self._n, [0] * self._n
pv, pe = [0] * self._n, [0] * self._n
vis = [False] * self._n
def dual_ref():
for i in range(self._n):
dist[i] = NUMERIC_LIMITS
pv[i] = -1
pe[i] = -1
vis[i] = False
class Q:
def __init__(s, key, to):
s.key = key
s.to = to
def __lt__(s, r):
return s.key < r.key
que = []
dist[s] = 0
push(que, Q(0, s))
while len(que):
v = pop(que).to
if vis[v]: continue
vis[v] = True
if v == t: break
for i in range(len(self.g[v])):
e = self.g[v][i]
if vis[e.to] or not e.cap: continue
cost = e.cost - dual[e.to] + dual[v]
if dist[e.to] - dist[v] > cost:
dist[e.to] = dist[v] + cost
pv[e.to] = v
pe[e.to] = i
push(que, Q(dist[e.to], e.to))
if not vis[t]: return False
for v in range(self._n):
if not vis[v]: continue
dual[v] -= dist[t] - dist[v]
return True
flow = 0
cost, prev_cost = 0, -1
result = []
result.append([flow, cost])
while flow < flow_limit:
if not dual_ref(): break
c = flow_limit - flow
v = t
while v != s:
c = min(c, self.g[pv[v]][pe[v]].cap)
v = pv[v]
v = t
while v != s:
e = self.g[pv[v]][pe[v]]
e.cap -= c
self.g[v][e.rev].cap += c
v = pv[v]
d = -dual[s]
flow += c
cost += c * d
if prev_cost == d:
result.pop()
result.append([flow, cost])
prev_cost = cost
return result
class _edge:
def __init__(s, to, rev, cap, cost):
s.to, s.rev = to, rev
s.cap, s.cost = cap, cost
#-------最強ライブラリここまで------
def main():
import sys
input = sys.stdin.readline
N, K = list(map(int, input().split()))
A = [list(map(int, input().split())) for _ in range(N)]
BIG = 10 ** 9
g = mcf_graph(2 * N + 2)
s = 2 * N
t = 2 * N + 1
g.add_edge(s, t, N * K, BIG)
# k,0|1,A[i][j]|k,0
# 列0 ー 行0
# / × \
# s ー 列1 米 行1 ー t
# \ × /
# 列i ー 行j
for i in range(N):
g.add_edge(s, i, K, 0)
g.add_edge(N + i, t, K, 0)
for i in range(N):
for j in range(N):
g.add_edge(i, N + j, 1, BIG - A[i][j])
result = g.flow(s, t, N * K)
print((N * K * BIG - result[1]))
grid = [["."] * N for _ in range(N)]
edges = g.edges()
for e in edges:
if e.frm == s or e.to == t or e.flow == 0: continue
grid[e.frm][e.to - N] = "X"
for g in grid:
print(("".join(g)))
main()
| import heapq
# numeric_limitsわかんね
NUMERIC_LIMITS = 10 ** 18
class mcf_graph:
pos = []
def __init__ (s, n):
s._n = n
s.g = [[] for _ in range(n)]
def add_edge(s, frm, to, cap, cost):
m = len(s.pos)
s.pos.append([frm, len(s.g[frm])])
s.g[frm].append(s._edge(to, len(s.g[to]), cap, cost))
s.g[to].append(s._edge(frm, len(s.g[frm]) - 1, 0, -cost))
return m
class edge:
def __init__(s, frm, to, cap, flow, cost):
s.frm, s.to = frm, to
s.cap, s.flow, s.cost = cap, flow, cost
def get_edge(s, i):
m = len(s.pos)
_e = s.g[s.pos[i][0]][s.pos[i][1]]
_re = s.g[_e.to][_e.rev]
return s.edge(s.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)
def edges(s):
return [s.get_edge(i) for i in range(len(s.pos))]
def flow(self, s, t, flow_limit = NUMERIC_LIMITS):
return self.slope(s, t, flow_limit)[-1]
def slope(self, s, t, flow_limit = NUMERIC_LIMITS):
#priority_queueの代わり
push = heapq.heappush
pop = heapq.heappop
dual, dist = [0] * self._n, [0] * self._n
pv, pe = [0] * self._n, [0] * self._n
vis = [False] * self._n
def dual_ref():
for i in range(self._n):
dist[i] = NUMERIC_LIMITS
pv[i] = -1
pe[i] = -1
vis[i] = False
class Q:
def __init__(s, key, to):
s.key = key
s.to = to
def __lt__(s, r):
return s.key < r.key
que = []
dist[s] = 0
push(que, Q(0, s))
while len(que):
v = pop(que).to
if vis[v]: continue
vis[v] = True
if v == t: break
for i in range(len(self.g[v])):
e = self.g[v][i]
if vis[e.to] or not e.cap: continue
cost = e.cost - dual[e.to] + dual[v]
if dist[e.to] - dist[v] > cost:
dist[e.to] = dist[v] + cost
pv[e.to] = v
pe[e.to] = i
push(que, Q(dist[e.to], e.to))
if not vis[t]: return False
for v in range(self._n):
if not vis[v]: continue
dual[v] -= dist[t] - dist[v]
return True
flow = 0
cost, prev_cost = 0, -1
result = []
result.append([flow, cost])
while flow < flow_limit:
if not dual_ref(): break
c = flow_limit - flow
v = t
while v != s:
c = min(c, self.g[pv[v]][pe[v]].cap)
v = pv[v]
v = t
while v != s:
e = self.g[pv[v]][pe[v]]
e.cap -= c
self.g[v][e.rev].cap += c
v = pv[v]
d = -dual[s]
flow += c
cost += c * d
if prev_cost == d:
result.pop()
result.append([flow, cost])
prev_cost = cost
return result
class _edge:
def __init__(s, to, rev, cap, cost):
s.to, s.rev = to, rev
s.cap, s.cost = cap, cost
#-------最強ライブラリここまで------
def main():
N, K = list(map(int, input().split()))
A = [list(map(int, input().split())) for _ in range(N)]
BIG = 10 ** 9
g = mcf_graph(2 * N + 2)
s = 2 * N
t = 2 * N + 1
g.add_edge(s, t, N * K, BIG)
# k,0|1,A[i][j]|k,0
# 列0 ー 行0
# / × \
# s ー 列1 米 行1 ー t
# \ × /
# 列i ー 行j
for i in range(N):
g.add_edge(s, i, K, 0)
g.add_edge(N + i, t, K, 0)
for i in range(N):
for j in range(N):
g.add_edge(i, N + j, 1, BIG - A[i][j])
result = g.flow(s, t, N * K)
print((N * K * BIG - result[1]))
grid = [["."] * N for _ in range(N)]
edges = g.edges()
for e in edges:
if e.frm == s or e.to == t or e.flow == 0: continue
grid[e.frm][e.to - N] = "X"
for g in grid:
print(("".join(g)))
main()
| p02562 |
import heapq
# numeric_limitsわかんね
NUMERIC_LIMITS = 10 ** 18
class mcf_graph:
def __init__ (s, n):
s._n = n
s.g = [[] for _ in range(n)]
s.pos = []
def add_edge(s, frm, to, cap, cost):
m = len(s.pos)
s.pos.append([frm, len(s.g[frm])])
s.g[frm].append(s._edge(to, len(s.g[to]), cap, cost))
s.g[to].append(s._edge(frm, len(s.g[frm]) - 1, 0, -cost))
return m
class edge:
__slots__ = "frm", "to", "cap", "flow", "cost"
def __init__(s, frm, to, cap, flow, cost):
s.frm, s.to = frm, to
s.cap, s.flow, s.cost = cap, flow, cost
def get_edge(s, i):
_e = s.g[s.pos[i][0]][s.pos[i][1]]
_re = s.g[_e.to][_e.rev]
return s.edge(s.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)
def edges(s):
for i in range(len(s.pos)):
yield s.get_edge(i)
def flow(self, s, t, flow_limit = NUMERIC_LIMITS):
return self.slope(s, t, flow_limit)[-1]
def dual_ref(self, s, t):
#priority_queueの代わり
push = heapq.heappush
pop = heapq.heappop
dist = [NUMERIC_LIMITS] * self._n
self.pv = [-1] * self._n
self.pe = [-1] * self._n
vis = [False] * self._n
class Q:
def __init__(s, key, to):
s.key = key
s.to = to
def __lt__(s, r):
return s.key < r.key
que = []
dist[s] = 0
push(que, Q(0, s))
while que:
v = pop(que).to
if vis[v]: continue
vis[v] = True
if v == t: break
for i in range(len(self.g[v])):
e = self.g[v][i]
if vis[e.to] or not e.cap: continue
cost = e.cost - self.dual[e.to] + self.dual[v]
if dist[e.to] - dist[v] > cost:
dist[e.to] = dist[v] + cost
self.pv[e.to] = v
self.pe[e.to] = i
push(que, Q(dist[e.to], e.to))
if not vis[t]: return False
for v in range(self._n):
if not vis[v]: continue
self.dual[v] -= dist[t] - dist[v]
return True
def slope(self, s, t, flow_limit = NUMERIC_LIMITS):
self.dual = [0] * self._n
flow = 0
cost, prev_cost = 0, -1
result = [(flow,cost)]
while flow < flow_limit:
if not self.dual_ref(s, t): break
c = flow_limit - flow
v = t
while v != s:
c = min(c, self.g[self.pv[v]][self.pe[v]].cap)
v = self.pv[v]
v = t
while v != s:
e = self.g[self.pv[v]][self.pe[v]]
e.cap -= c
self.g[v][e.rev].cap += c
v = self.pv[v]
d = -self.dual[s]
flow += c
cost += c * d
if prev_cost == d:
result.pop()
result.append((flow, cost))
prev_cost = cost
return result
class _edge:
__slots__ = "to", "rev", "cap", "cost"
def __init__(s, to, rev, cap, cost):
s.to, s.rev = to, rev
s.cap, s.cost = cap, cost
N, K = list(map(int, input().split()))
A = [tuple(map(int, input().split())) for _ in range(N)]
BIG = 10 ** 9
g = mcf_graph(2 * N + 2)
s = 2 * N
t = 2 * N + 1
g.add_edge(s, t, N * K, BIG)
# k,0|1,A[i][j]|k,0
# 列0 ー 行0
# / × \
# s ー 列1 米 行1 ー t
# \ × /
# 列i ー 行j
for i in range(N):
g.add_edge(s, i, K, 0)
g.add_edge(N + i, t, K, 0)
for i in range(N):
for j in range(N):
g.add_edge(i, N + j, 1, BIG - A[i][j])
result = g.flow(s, t, N * K)
print((N * K * BIG - result[1]))
grid = [["."] * N for _ in range(N)]
edges = g.edges()
for e in edges:
if e.frm == s or e.to == t or e.flow == 0: continue
grid[e.frm][e.to - N] = "X"
for g in grid:
print(("".join(g))) | import heapq
# numeric_limitsわかんね
NUMERIC_LIMITS = 10 ** 18
class mcf_graph:
def __init__ (s, n):
s._n = n
s.g = [[] for _ in range(n)]
s.pos = []
def add_edge(s, frm, to, cap, cost):
m = len(s.pos)
s.pos.append([frm, len(s.g[frm])])
s.g[frm].append(s._edge(to, len(s.g[to]), cap, cost))
s.g[to].append(s._edge(frm, len(s.g[frm]) - 1, 0, -cost))
return m
class edge:
__slots__ = "frm", "to", "cap", "flow", "cost"
def __init__(s, frm, to, cap, flow, cost):
s.frm, s.to = frm, to
s.cap, s.flow, s.cost = cap, flow, cost
def get_edge(s, i):
_e = s.g[s.pos[i][0]][s.pos[i][1]]
_re = s.g[_e.to][_e.rev]
return s.edge(s.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)
def edges(s):
for i in range(len(s.pos)):
yield s.get_edge(i)
def flow(self, s, t, flow_limit = NUMERIC_LIMITS):
return self.slope(s, t, flow_limit)[-1]
def dual_ref(self, s, t):
#priority_queueの代わり
push = heapq.heappush
pop = heapq.heappop
dist = [NUMERIC_LIMITS] * self._n
self.pv = [-1] * self._n
self.pe = [-1] * self._n
vis = [False] * self._n
que = []
dist[s] = 0
push(que, (0, s))
while que:
k, v = pop(que)
if vis[v]: continue
vis[v] = True
if v == t: break
for i in range(len(self.g[v])):
e = self.g[v][i]
if vis[e.to] or not e.cap: continue
cost = e.cost - self.dual[e.to] + self.dual[v]
if dist[e.to] - dist[v] > cost:
dist[e.to] = dist[v] + cost
self.pv[e.to] = v
self.pe[e.to] = i
push(que,(dist[e.to], e.to))
if not vis[t]: return False
for v in range(self._n):
if not vis[v]: continue
self.dual[v] -= dist[t] - dist[v]
return True
def slope(self, s, t, flow_limit = NUMERIC_LIMITS):
self.dual = [0] * self._n
flow = 0
cost, prev_cost = 0, -1
result = [(flow,cost)]
while flow < flow_limit:
if not self.dual_ref(s, t): break
c = flow_limit - flow
v = t
while v != s:
c = min(c, self.g[self.pv[v]][self.pe[v]].cap)
v = self.pv[v]
v = t
while v != s:
e = self.g[self.pv[v]][self.pe[v]]
e.cap -= c
self.g[v][e.rev].cap += c
v = self.pv[v]
d = -self.dual[s]
flow += c
cost += c * d
if prev_cost == d:
result.pop()
result.append((flow, cost))
prev_cost = cost
return result
class _edge:
__slots__ = "to", "rev", "cap", "cost"
def __init__(s, to, rev, cap, cost):
s.to, s.rev = to, rev
s.cap, s.cost = cap, cost
N, K = list(map(int, input().split()))
A = [tuple(map(int, input().split())) for _ in range(N)]
BIG = 10 ** 9
g = mcf_graph(2 * N + 2)
s = 2 * N
t = 2 * N + 1
g.add_edge(s, t, N * K, BIG)
# k,0|1,A[i][j]|k,0
# 列0 ー 行0
# / × \
# s ー 列1 米 行1 ー t
# \ × /
# 列i ー 行j
for i in range(N):
g.add_edge(s, i, K, 0)
g.add_edge(N + i, t, K, 0)
for i in range(N):
for j in range(N):
g.add_edge(i, N + j, 1, BIG - A[i][j])
result = g.flow(s, t, N * K)
print((N * K * BIG - result[1]))
grid = [["."] * N for _ in range(N)]
edges = g.edges()
for e in edges:
if e.frm == s or e.to == t or e.flow == 0: continue
grid[e.frm][e.to - N] = "X"
for g in grid:
print(("".join(g))) | p02562 |
from heapq import heappush, heappop
class MinCostFlow:
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap, cost):
forward = [to, cap, cost, None]
backward = forward[3] = [fr, 0, -cost, forward]
self.G[fr].append(forward)
self.G[to].append(backward)
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0]*N
prv_v = [0]*N
prv_e = [None]*N
d0 = [INF]*N
dist = [INF]*N
while f:
dist[:] = d0
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
r0 = dist[v] + H[v]
for e in G[v]:
w, cap, cost, _ = e
if cap > 0 and r0 + cost - H[w] < dist[w]:
dist[w] = r = r0 + cost - H[w]
prv_v[w] = v; prv_e[w] = e
heappush(que, (r, w))
if dist[t] == INF:
return None
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, prv_e[v][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = prv_e[v]
e[1] -= d
e[3][1] += d
v = prv_v[v]
return res
N,K = list(map(int,input().split()))
A = [list(map(int,input().split())) for i in range(N)]
G = MinCostFlow(N**2+2*N+3)
G.add_edge(0,N**2+2*N+2,10**18,0)
G.add_edge(N**2+2*N+2,N**2+2*N+1,10**18,0)
for i in range(N):
G.add_edge(0,i+1,K,0)
for j in range(N):
node = N * i + j + 2*N + 1
G.add_edge(i+1,node,1,-A[i][j])
G.add_edge(node,N+1+j,1,0)
for j in range(N):
G.add_edge(N+1+j,N**2+2*N+1,K,0)
f = G.flow(0,N**2+2*N+1,N**2)
print((-f))
res = [["." for j in range(N)] for i in range(N)]
for i in range(N):
for Node,cap,_,_ in G.G[i+1]:
if Node == 0:
continue
node = Node - (2*N+1)
px,py = node//N,node%N
if cap==0:
res[px][py] = "X"
for i in range(N):
print(("".join(res[i]))) | from heapq import heappush, heappop
class MinCostFlow:
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap, cost):
forward = [to, cap, cost, None]
backward = forward[3] = [fr, 0, -cost, forward]
self.G[fr].append(forward)
self.G[to].append(backward)
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0]*N
prv_v = [0]*N
prv_e = [None]*N
d0 = [INF]*N
dist = [INF]*N
while f:
dist[:] = d0
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
r0 = dist[v] + H[v]
for e in G[v]:
w, cap, cost, _ = e
if cap > 0 and r0 + cost - H[w] < dist[w]:
dist[w] = r = r0 + cost - H[w]
prv_v[w] = v; prv_e[w] = e
heappush(que, (r, w))
if dist[t] == INF:
return None
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, prv_e[v][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = prv_e[v]
e[1] -= d
e[3][1] += d
v = prv_v[v]
return res
N,K = list(map(int,input().split()))
A = [list(map(int,input().split())) for i in range(N)]
G = MinCostFlow(2*N+3)
G.add_edge(0,2*N+2,10**18,0)
G.add_edge(2*N+2,2*N+1,10**18,0)
for i in range(N):
G.add_edge(0,i+1,K,0)
for j in range(N):
G.add_edge(i+1,N+1+j,1,-A[i][j])
for j in range(N):
G.add_edge(N+1+j,2*N+1,K,0)
f = G.flow(0,2*N+1,N**2)
print((-f))
res = [["." for j in range(N)] for i in range(N)]
for i in range(N):
for w, cap, _, _ in G.G[i+1]:
if N+1<=w<=2*N:
j = w - (N+1)
if cap==0:
res[i][j] = "X"
for i in range(N):
print(("".join(res[i])))
| p02562 |
import heapq
class mcf_graph:
def __init__(self, n=0):
self._n = n
self.g = [[] for _ in range(n)]
self.pos = []
def add_edge(self, frm, to, cap, cost):
m = len(self.pos)
e1 = self._edge(to, cap, cost)
e2 = self._edge(frm, 0, -cost)
e1.rev = e2
e2.rev = e1
self.pos.append(e1)
self.g[frm].append(e1)
self.g[to].append(e2)
return m
class edge:
def __init__(self, frm, to, cap, flow, cost):
self.frm = frm
self.to = to
self.cap = cap
self.flow = flow
self.cost = cost
def __iter__(self):
yield self.frm
yield self.to
yield self.cap
yield self.flow
yield self.cost
def get_edge(self, i):
e = self.pos[i]
re = e.rev
return self.edge(re.to, e.to, e.cap + re.cap, re.cap, e.cost)
def edges(self):
return [self.get_edge(i) for i in range(len(self.pos))]
def flow(self, s, t, flow_limit=float('inf')):
return self.slope(s, t, flow_limit)[-1]
def slope(self, s, t, flow_limit=float('inf')):
n = self._n
g = self.g
dual = [0] * n
dist = [0] * n
pv = [0] * n
pe = [None] * n
vis = [False] * n
INF = float('inf')
def dual_ref():
for i in range(n):
dist[i] = INF
vis[i] = False
dist[s] = 0
que = [(0, s)]
while que:
_, v = heapq.heappop(que)
if vis[v]:
continue
vis[v] = True
if v == t:
break
for e in g[v]:
w = e.to
if vis[w] or not e.cap:
continue
cost = e.cost - dual[w] + dual[v]
if dist[w] - dist[v] > cost:
dist[w] = dist[v] + cost
pv[w] = v
pe[w] = e
heapq.heappush(que, (dist[w], w))
else:
return False
for v in range(n):
if not vis[v]:
continue
dual[v] -= dist[t] - dist[v]
return True
flow = 0
cost = 0
prev_cost = -1
result = [(flow, cost)]
while flow < flow_limit:
if not dual_ref():
break
c = flow_limit - flow
v = t
while v != s:
c = min(c, pe[v].cap)
v = pv[v]
v = t
while v != s:
e = pe[v]
e.cap -= c
e.rev.cap += c
v = pv[v]
d = -dual[s]
flow += c
cost += c * d
if prev_cost == d:
result.pop()
result.append((flow, cost))
prev_cost = cost
return result
class _edge:
def __init__(self, to, cap, cost):
self.to = to
self.cap = cap
self.cost = cost
n, k = list(map(int, input().split()))
a = [list(map(int, input().split())) for _ in range(n)]
mx = max(aij for ai in a for aij in ai)
s = n * n
t = s + 1
rs = t + 1
cs = rs + n
vcnt = cs + n
d = mcf_graph(vcnt)
for i in range(n):
d.add_edge(s, rs + i, k, 0)
for i in range(n):
for j in range(n):
d.add_edge(rs + i, i * n + j, 1, mx - a[i][j])
for i in range(n):
for j in range(n):
d.add_edge(i * n + j, cs + j, 1, 0)
for j in range(n):
d.add_edge(cs + j, t, k, 0)
d.add_edge(s, t, n * n, mx)
_, res = d.flow(s, t, n * n)
print((n * n * mx - res))
ans = [['.'] * n for _ in range(n)]
for frm, to, cap, flow, cost in d.edges():
if frm < n * n and flow:
i, j = frm // n, frm % n
ans[i][j] = 'X'
for t in ans:
print((''.join(t))) | import heapq
class mcf_graph:
def __init__(self, n=0):
self._n = n
self.g = [[] for _ in range(n)]
self.pos = []
def add_edge(self, frm, to, cap, cost):
m = len(self.pos)
e1 = self._edge(to, cap, cost)
e2 = self._edge(frm, 0, -cost)
e1.rev = e2
e2.rev = e1
self.pos.append(e1)
self.g[frm].append(e1)
self.g[to].append(e2)
return m
class edge:
def __init__(self, frm, to, cap, flow, cost):
self.frm = frm
self.to = to
self.cap = cap
self.flow = flow
self.cost = cost
def __iter__(self):
yield self.frm
yield self.to
yield self.cap
yield self.flow
yield self.cost
def get_edge(self, i):
e = self.pos[i]
re = e.rev
return self.edge(re.to, e.to, e.cap + re.cap, re.cap, e.cost)
def edges(self):
return [self.get_edge(i) for i in range(len(self.pos))]
def flow(self, s, t, flow_limit=float('inf')):
return self.slope(s, t, flow_limit)[-1]
def slope(self, s, t, flow_limit=float('inf')):
pop, push = heapq.heappop, heapq.heappush
n = self._n
g = self.g
dual = [0] * n
dist = [0] * n
pv = [0] * n
pe = [None] * n
vis = [False] * n
INF = float('inf')
flow = 0
cost = 0
prev_cost = -1
result = [(flow, cost)]
while flow < flow_limit:
for i in range(n):
dist[i] = INF
vis[i] = False
dist[s] = 0
que = [(0, s)]
while que:
_, v = pop(que)
if vis[v]:
continue
vis[v] = True
if v == t:
break
for e in g[v]:
w = e.to
if vis[w] or not e.cap:
continue
ndist = dist[v] + e.cost - dual[w] + dual[v]
if ndist < dist[w]:
dist[w] = ndist
pv[w] = v
pe[w] = e
push(que, (dist[w], w))
else:
break
for v in range(n):
if not vis[v]:
continue
dual[v] -= dist[t] - dist[v]
c = flow_limit - flow
v = t
while v != s:
c = min(c, pe[v].cap)
v = pv[v]
v = t
while v != s:
e = pe[v]
e.cap -= c
e.rev.cap += c
v = pv[v]
d = -dual[s]
flow += c
cost += c * d
if prev_cost == d:
result[-1] = (flow, cost)
else:
result.append((flow, cost))
prev_cost = cost
return result
class _edge:
def __init__(self, to, cap, cost):
self.to = to
self.cap = cap
self.cost = cost
class _edge:
def __init__(self, to, cap, cost):
self.to = to
self.cap = cap
self.cost = cost
n, k = list(map(int, input().split()))
a = [list(map(int, input().split())) for _ in range(n)]
mx = max(aij for ai in a for aij in ai)
s = n * n
t = s + 1
rs = t + 1
cs = rs + n
vcnt = cs + n
d = mcf_graph(vcnt)
for i in range(n):
d.add_edge(s, rs + i, k, 0)
for i in range(n):
for j in range(n):
d.add_edge(rs + i, i * n + j, 1, mx - a[i][j])
for i in range(n):
for j in range(n):
d.add_edge(i * n + j, cs + j, 1, 0)
for j in range(n):
d.add_edge(cs + j, t, k, 0)
d.add_edge(s, t, n * n, mx)
_, res = d.flow(s, t, n * n)
print((n * n * mx - res))
ans = [['.'] * n for _ in range(n)]
for frm, to, cap, flow, cost in d.edges():
if frm < n * n and flow:
i, j = frm // n, frm % n
ans[i][j] = 'X'
for t in ans:
print((''.join(t))) | p02562 |
import sys
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(eval(input()))
def MAP(): return list(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')
sys.setrecursionlimit(10**9)
INF = 10**18
MOD = 10**9 + 7
EPS = 10**-10
class MinCostFlow:
""" 最小費用流(ダイクストラ版2):O(F*V^2) """
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
self.pos = []
def copy(self):
res = MinCostFlow(self.N)
res.G = [[a[:] for a in b] for b in self.G]
res.pos = [a[:] for a in self.pos]
return res
def add_edge(self, fr, to, cap, cost):
self.pos.append((fr, len(self.G[fr])))
self.G[fr].append([to, cap, cost, len(self.G[to])])
self.G[to].append([fr, 0, -cost, len(self.G[fr])-1])
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0] * N
prv_v = [0] * N
prv_e = [0] * N
while f:
dist = [INF] * N
dist[s] = 0
used = [False] * N
while True:
v = -1
for u in range(N):
if not used[u] and (v == -1 or dist[u] < dist[v]):
v = u
if v == -1:
break
used[v] = True
for i, (to, cap, cost, _) in enumerate(G[v]):
if cap > 0 and dist[to] > dist[v] + cost + H[v] - H[to]:
dist[to] = dist[v] + cost + H[v] - H[to]
prv_v[to] = v; prv_e[to] = i
if dist[t] == INF:
return INF
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, G[prv_v[v]][prv_e[v]][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = G[prv_v[v]][prv_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prv_v[v]
return res
def get_edge(self, i):
e = self.G[self.pos[i][0]][self.pos[i][1]]
re = self.G[e[0]][e[3]]
# from, to, cap, flow, cost
return (self.pos[i][0], e[0], e[1]+re[1], re[1], e[2])
def get_edges(self):
M = len(self.pos)
res = []
for i in range(M):
res.append(self.get_edge(i))
return res
def trisearch_min(lo, hi, func):
""" 三分探索 """
while lo+2 < hi:
m1 = (lo*2+hi) // 3
m2 = (lo+hi*2) // 3
res1 = func(m1)
res2 = func(m2)
if res1 <= res2:
hi = m2
else:
lo = m1
return m1, m2
N, K = MAP()
grid = [[] for i in range(N)]
for i in range(N):
grid[i] = LIST()
offset = 10**12
mcf = MinCostFlow(N*2+2)
s = N*2
t = N*2 + 1
for i in range(N):
mcf.add_edge(s, i, K, offset)
mcf.add_edge(N+i, t, K, offset)
for j in range(N):
mcf.add_edge(i, N+j, 1, offset-grid[i][j])
def check(x):
global mcf
tmp = mcf.copy()
res = mcf.flow(s, t, x)
if res != INF:
res -= offset * x * 3
mcf = tmp
return res
m1, m2 = trisearch_min(-1, N*N+1, check)
x = m1 if check(m1) <= check(m2) else m2
mn = mcf.flow(s, t, x)
mn -= offset * x * 3
ans = [['.' for j in range(N)] for i in range(N)]
edges = mcf.get_edges()
for fr, to, cap, f, c in edges:
if fr != s and to != t and f:
h = fr
w = to - N
ans[h][w] = 'X'
print((-mn))
for i in range(N):
print((''.join(ans[i])))
| import sys
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(eval(input()))
def MAP(): return list(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')
sys.setrecursionlimit(10**9)
INF = 10**18
MOD = 10**9 + 7
EPS = 10**-10
class MinCostFlow:
""" 最小費用流(ダイクストラ版):O(F*E*logV) """
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
self.pos = []
def copy(self):
res = MinCostFlow(self.N)
res.G = [[a[:] for a in b] for b in self.G]
res.pos = [a[:] for a in self.pos]
return res
def add_edge(self, fr, to, cap, cost):
self.pos.append((fr, len(self.G[fr])))
self.G[fr].append([to, cap, cost, len(self.G[to])])
self.G[to].append([fr, 0, -cost, len(self.G[fr])-1])
def flow(self, s, t, f):
from heapq import heappush, heappop
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0] * N
prv_v = [0] * N
prv_e = [0] * N
while f:
dist = [INF] * N
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
for i, (to, cap, cost, _) in enumerate(G[v]):
if cap > 0 and dist[to] > dist[v] + cost + H[v] - H[to]:
dist[to] = r = dist[v] + cost + H[v] - H[to]
prv_v[to] = v; prv_e[to] = i
heappush(que, (r, to))
if dist[t] == INF:
return INF
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, G[prv_v[v]][prv_e[v]][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = G[prv_v[v]][prv_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prv_v[v]
return res
def get_edge(self, i):
e = self.G[self.pos[i][0]][self.pos[i][1]]
re = self.G[e[0]][e[3]]
# from, to, cap, flow, cost
return (self.pos[i][0], e[0], e[1]+re[1], re[1], e[2])
def get_edges(self):
M = len(self.pos)
res = []
for i in range(M):
res.append(self.get_edge(i))
return res
N, K = MAP()
grid = [[] for i in range(N)]
for i in range(N):
grid[i] = LIST()
offset = 10**12
mcf = MinCostFlow(N*2+2)
s = N*2
t = N*2 + 1
# 利益なしだけどいくらでも通れる辺を追加して、到達不可にならないようにする
mcf.add_edge(s, t, N*N, offset)
for i in range(N):
mcf.add_edge(s, i, K, 0)
mcf.add_edge(N+i, t, K, 0)
for j in range(N):
mcf.add_edge(i, N+j, 1, offset-grid[i][j])
mn = mcf.flow(s, t, N*N)
mn -= offset*N*N
ans = [['.' for j in range(N)] for i in range(N)]
edges = mcf.get_edges()
for fr, to, cap, f, c in edges:
if fr != s and to != t and f:
h = fr
w = to - N
ans[h][w] = 'X'
print((-mn))
for i in range(N):
print((''.join(ans[i])))
| p02562 |
import sys
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(eval(input()))
def MAP(): return list(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')
sys.setrecursionlimit(10**9)
INF = 10**18
MOD = 10**9 + 7
EPS = 10**-10
class MinCostFlow:
""" 最小費用流(ダイクストラ版):O(F*E*logV) """
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
self.pos = []
def copy(self):
res = MinCostFlow(self.N)
res.G = [[a[:] for a in b] for b in self.G]
res.pos = [a[:] for a in self.pos]
return res
def add_edge(self, fr, to, cap, cost):
self.pos.append((fr, len(self.G[fr])))
self.G[fr].append([to, cap, cost, len(self.G[to])])
self.G[to].append([fr, 0, -cost, len(self.G[fr])-1])
def flow(self, s, t, f):
from heapq import heappush, heappop
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0] * N
prv_v = [0] * N
prv_e = [0] * N
while f:
dist = [INF] * N
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
for i, (to, cap, cost, _) in enumerate(G[v]):
if cap > 0 and dist[to] > dist[v] + cost + H[v] - H[to]:
dist[to] = r = dist[v] + cost + H[v] - H[to]
prv_v[to] = v; prv_e[to] = i
heappush(que, (r, to))
if dist[t] == INF:
return INF
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, G[prv_v[v]][prv_e[v]][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = G[prv_v[v]][prv_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prv_v[v]
return res
def get_edge(self, i):
e = self.G[self.pos[i][0]][self.pos[i][1]]
re = self.G[e[0]][e[3]]
# from, to, cap, flow, cost
return (self.pos[i][0], e[0], e[1]+re[1], re[1], e[2])
def get_edges(self):
M = len(self.pos)
res = []
for i in range(M):
res.append(self.get_edge(i))
return res
N, K = MAP()
grid = [[] for i in range(N)]
for i in range(N):
grid[i] = LIST()
offset = 10**12
mcf = MinCostFlow(N*2+2)
s = N*2
t = N*2 + 1
# 利益なしだけどいくらでも通れる辺を追加して、到達不可にならないようにする
mcf.add_edge(s, t, N*N, offset)
for i in range(N):
mcf.add_edge(s, i, K, 0)
mcf.add_edge(N+i, t, K, 0)
for j in range(N):
mcf.add_edge(i, N+j, 1, offset-grid[i][j])
mn = mcf.flow(s, t, N*N)
mn -= offset*N*N
ans = [['.' for j in range(N)] for i in range(N)]
edges = mcf.get_edges()
for fr, to, cap, f, c in edges:
if fr != s and to != t and f:
h = fr
w = to - N
ans[h][w] = 'X'
print((-mn))
for i in range(N):
print((''.join(ans[i])))
| import sys
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(eval(input()))
def MAP(): return list(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')
sys.setrecursionlimit(10**9)
INF = 10**18
MOD = 10**9 + 7
EPS = 10**-10
class MinCostFlow:
""" 最小費用流(ダイクストラ版2):O(F*V^2) """
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
self.pos = []
def copy(self):
res = MinCostFlow(self.N)
res.G = [[a[:] for a in b] for b in self.G]
res.pos = [a[:] for a in self.pos]
return res
def add_edge(self, fr, to, cap, cost):
self.pos.append((fr, len(self.G[fr])))
self.G[fr].append([to, cap, cost, len(self.G[to])])
self.G[to].append([fr, 0, -cost, len(self.G[fr])-1])
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0] * N
prv_v = [0] * N
prv_e = [0] * N
while f:
dist = [INF] * N
dist[s] = 0
used = [False] * N
while True:
v = -1
for u in range(N):
if not used[u] and (v == -1 or dist[u] < dist[v]):
v = u
if v == -1:
break
used[v] = True
for i, (to, cap, cost, _) in enumerate(G[v]):
if cap > 0 and dist[to] > dist[v] + cost + H[v] - H[to]:
dist[to] = dist[v] + cost + H[v] - H[to]
prv_v[to] = v; prv_e[to] = i
if dist[t] == INF:
return INF
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, G[prv_v[v]][prv_e[v]][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = G[prv_v[v]][prv_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prv_v[v]
return res
def get_edge(self, i):
e = self.G[self.pos[i][0]][self.pos[i][1]]
re = self.G[e[0]][e[3]]
# from, to, cap, flow, cost
return (self.pos[i][0], e[0], e[1]+re[1], re[1], e[2])
def get_edges(self):
M = len(self.pos)
res = []
for i in range(M):
res.append(self.get_edge(i))
return res
N, K = MAP()
grid = [[] for i in range(N)]
for i in range(N):
grid[i] = LIST()
offset = 10**12
mcf = MinCostFlow(N*2+2)
s = N*2
t = N*2 + 1
# 利益なしだけどいくらでも通れる辺を追加して、到達不可にならないようにする
mcf.add_edge(s, t, N*N, offset)
for i in range(N):
mcf.add_edge(s, i, K, 0)
mcf.add_edge(N+i, t, K, 0)
for j in range(N):
mcf.add_edge(i, N+j, 1, offset-grid[i][j])
mn = mcf.flow(s, t, N*N)
mn -= offset*N*N
ans = [['.' for j in range(N)] for i in range(N)]
edges = mcf.get_edges()
for fr, to, cap, f, c in edges:
if fr != s and to != t and f:
h = fr
w = to - N
ans[h][w] = 'X'
print((-mn))
for i in range(N):
print((''.join(ans[i])))
| p02562 |
import sys
input=sys.stdin.readline
import heapq
n,q=list(map(int,input().split()))
l=[list(map(int,input().split())) for i in range(n)]
L1=[]
for i in range(n):
L1.append([l[i][0]-l[i][2],1,l[i][2]])
L1.append([l[i][1]-l[i][2],-1,l[i][2]])
for i in range(q):
L1.append([int(eval(input())),2,0])
L1.sort()
L2=[]
heapq.heapify(L2)
L3=[]
L3=set(L3)
ans=[]
for i in range(len(L1)):
if L1[i][1]==1:
heapq.heappush(L2,L1[i][2])
L3.add(L1[i][2])
elif L1[i][1]==-1:
L3.remove(L1[i][2])
else:
while L2 and L2[0] not in L3:
heapq.heappop(L2)
if L2:
print((L2[0]))
else:
print((-1)) | import sys
input=sys.stdin.readline
import heapq
n,q=list(map(int,input().split()))
l=[list(map(int,input().split())) for i in range(n)]
L1=[]
for i in range(n):
L1.append((l[i][0]-l[i][2],1,l[i][2]))
L1.append((l[i][1]-l[i][2],-1,l[i][2]))
for i in range(q):
L1.append((int(eval(input())),2,0))
L1.sort()
L2=[]
heapq.heapify(L2)
L3=[]
L3=set(L3)
for i in range(len(L1)):
if L1[i][1]==1:
heapq.heappush(L2,L1[i][2])
L3.add(L1[i][2])
elif L1[i][1]==-1:
L3.remove(L1[i][2])
else:
while L2 and L2[0] not in L3:
heapq.heappop(L2)
if L2:
print((L2[0]))
else:
print((-1)) | p03033 |
import sys
from heapq import *
input = sys.stdin.readline
def main():
n, q = list(map(int, input().split()))
key = []
for i in range(n):
s, t, x = list(map(int, input().split()))
l, r = max(0, s-x), max(0, t-x)
key.append((l, 1, x))
key.append((r, -1, x))
key.sort()
judge = []
now = set()
already = dict()
index = 0
ans = -1
for i in range(q):
d = int(eval(input()))
for i in range(index, 2*n):
s, j, x = key[i]
if s > d:
index = i
break
if j == 1:
heappush(judge, x)
now = now.union({x})
else:
now.discard(x)
if x in already:
already[x] += 1
else:
already[x] = 1
while judge:
if judge[0] in already and already[judge[0]] > 0:
already[judge[0]] -= 1
heappop(judge)
else:
break
if judge:
ans = judge[0]
else:
ans = -1
print(ans)
if __name__ == "__main__":
main() | import sys
from heapq import *
input = sys.stdin.readline
def main():
n, q = list(map(int, input().split()))
key = []
for i in range(n):
s, t, x = list(map(int, input().split()))
l, r = max(0, s-x), max(0, t-x)
key.append((l, 1, x))
key.append((r, -1, x))
for i in range(q):
d = int(eval(input()))
key.append((d, 2))
key.sort()
judge = []
already = dict()
for i in range(2*n+q):
k = key[i]
if k[1] == -1:
if k[2] in already:
already[k[2]] += 1
else:
already[k[2]] = 1
elif k[1] == 1:
heappush(judge, k[2])
else:
while judge:
if judge[0] in already and already[judge[0]] > 0:
already[judge[0]] -= 1
heappop(judge)
else:
break
if judge:
print((judge[0]))
else:
print((-1))
if __name__ == "__main__":
main()
| p03033 |
from heapq import heapify, heappush, heappop
INF = 1001001001
N, Q = list(map(int, input().split()))
STXs = [tuple(map(int, input().split())) for _ in range(N)]
Ds = [int(eval(input())) for _ in range(Q)]
#S-X, T-X, X
future_block = [(S - X, T - X, X) for S, T, X in STXs]
future_block.append((INF, INF, INF)) #sentinel
heapify(future_block)
#T-X, S-X, X
current_block = [(INF, INF, INF)] #sentinel
current_min_pair = (INF, INF, INF)
for D in Ds:
while future_block[0][0] <= D:
s_x, t_x, x = heappop(future_block)
if current_min_pair[2] > x:
current_min_pair = (t_x, s_x, x)
heappush(current_block, (t_x, s_x, x))
while current_block[0][0] <= D:
if current_min_pair == heappop(current_block):
current_min_pair = min(current_block, key = lambda t: t[2])
print((-1 if current_min_pair[2] == INF else current_min_pair[2]))
| from heapq import heapify, heappush, heappop
INF = 1001001001
N, Q = list(map(int, input().split()))
STXs = [tuple(map(int, input().split())) for _ in range(N)]
Ds = [int(eval(input())) for _ in range(Q)]
#S-X, T-X, X
future_block = [(S - X, T - X, X) for S, T, X in STXs]
future_block.append((INF, INF, INF)) #sentinel
heapify(future_block)
#T-X, S-X, X
current_block = [(INF, INF, INF)] #sentinel
current_min_pair = (INF, INF, INF)
for D in Ds:
while future_block[0][0] <= D:
s_x, t_x, x = heappop(future_block)
if current_min_pair[2] > x:
current_min_pair = (t_x, s_x, x)
heappush(current_block, (t_x, s_x, x))
search_min_flg = False
while current_block[0][0] <= D:
if current_min_pair == heappop(current_block):
search_min_flg = True
if search_min_flg:
current_min_pair = min(current_block, key = lambda t: t[2])
print((-1 if current_min_pair[2] == INF else current_min_pair[2]))
| p03033 |
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
from collections import Counter
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# map(int, input().split())
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
from collections import Counter
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# map(int, input().split())
N, Q = list(map(int, input().split()))
events = []
for i in range(N):
s, t, x = list(map(int, input().split()))
events.append((s - x, 0, x))
events.append((t - x, 1, x))
for i in range(Q):
d = int(eval(input()))
events.append((d, 2, i))
events = sorted(events)
q = [INF]
cnt = defaultdict(int)
ans = [INF] * Q
for a, b, c in events:
if b == 0:
heapq.heappush(q, c)
cnt[c] += 1
if b == 1:
cnt[c] -= 1
if b == 2:
while len(q) > 1 and cnt[q[0]] == 0:
heapq.heappop(q)
if q[0] == INF:
ans[c] = -1
else:
ans[c] = q[0]
for i in range(Q):
print((ans[i])) | import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
from collections import Counter
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# map(int, input().split())
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
from collections import Counter
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# map(int, input().split())
N, Q = list(map(int, input().split()))
events = []
for i in range(N):
s, t, x = list(map(int, input().split()))
events.append((s - x, 0, x))
events.append((t - x, 1, x))
for i in range(Q):
d = int(eval(input()))
events.append((d, 2, i))
events = sorted(events)
q = [INF]
cnt = defaultdict(int)
cnt[INF] = 1
ans = [INF] * Q
for a, b, c in events:
if b == 0:
heapq.heappush(q, c)
cnt[c] += 1
if b == 1:
cnt[c] -= 1
if b == 2:
while cnt[q[0]] == 0:
heapq.heappop(q)
if q[0] == INF:
ans[c] = -1
else:
ans[c] = q[0]
for i in range(Q):
print((ans[i])) | p03033 |
import heapq
N, Q = (int(i) for i in input().split())
L = [0] * (2 * N + Q)
for i in range(N):
S, T, X = (int(i) for i in input().split())
L[2 * i] = (S-X, X, 1)
L[2 * i + 1] = (T-X, X, -1)
for i in range(Q):
D = int(eval(input()))
L[2 * N + i] = (D, 10**9+1, 0)
L.sort()
Xs = set([])
XH = []
heapq.heapify(XH)
for t, X, f in L:
if f == 1:
Xs.add(X)
heapq.heappush(XH, X)
elif f == -1:
Xs.remove(X)
else:
if Xs:
while XH[0] not in Xs:
X = heapq.heappop(XH)
print((XH[0]))
else:
print("-1") | import sys
input = sys.stdin.readline
import heapq
N, Q = (int(i) for i in input().split())
L = [0] * (2 * N + Q)
for i in range(N):
S, T, X = (int(i) for i in input().split())
L[2 * i] = (S-X, 1, X)
L[2 * i + 1] = (T-X, -1, X)
for i in range(Q):
D = int(eval(input()))
L[2 * N + i] = (D, 2, 0)
L.sort()
Xs = set([])
XH = []
heapq.heapify(XH)
for t, f, X in L:
if f == 1:
Xs.add(X)
heapq.heappush(XH, X)
elif f == -1:
Xs.remove(X)
else:
if Xs:
while XH[0] not in Xs:
X = heapq.heappop(XH)
print((XH[0]))
else:
print("-1") | p03033 |
def main():
import sys
import heapq
N, Q = list(map(int, sys.stdin.readline().split()))
events = []
for i in range(N):
s, t, x = list(map(int, sys.stdin.readline().split()))
events.append((s - x, 1, x)) # 通行止め追加
events.append((t - x, -1, x)) # 通行止め削除
events.sort()
events.append([float('inf'), 'guard', None])
i = 0
closing = set()
hq = [] # 最小値を高速に入手するため
for q in range(Q):
d = int(eval(input()))
while d >= events[i][0]:
time, event, x = events[i]
if event == 1:
closing.add(x)
heapq.heappush(hq, x)
elif event == -1:
closing.remove(x)
i += 1
while hq and (hq[0] not in closing):
heapq.heappop(hq)
if hq:
print((hq[0]))
else:
print((-1))
if __name__ == '__main__':
main()
| def main():
import sys
import heapq
N, Q = list(map(int, sys.stdin.readline().split()))
events = []
for i in range(N):
s, t, x = list(map(int, sys.stdin.readline().split()))
events.append((s - x, 1, x)) # 通行止め追加
events.append((t - x, -1, x)) # 通行止め削除
for i in range(Q):
d = int(eval(input()))
events.append((d, 2, 0))
events.sort()
events.append([float('inf'), 'guard', None])
i = 0
closing = set()
hq = [] # 最小値を高速に入手するため
while d >= events[i][0]:
time, event, x = events[i]
if event == 1:
closing.add(x)
heapq.heappush(hq, x)
elif event == -1:
closing.remove(x)
else:
while hq and (hq[0] not in closing):
heapq.heappop(hq)
if hq:
print((hq[0]))
else:
print((-1))
i += 1
if __name__ == '__main__':
main()
| p03033 |
#D in [S_i-X_i,T_i-X_i) → Xiで止まる
import sys
input = sys.stdin.readline
N,Q = list(map(int,input().split()))
q = []
STX = [[int(x) for x in input().split()] for _ in range(N)]
for s,t,x in STX:
q.append((s-x,1,x)) # xで死ぬ
q.append((t-x,0,x)) # xで死ななくなる
for i in range(Q):
d = int(eval(input()))
q.append((d,2,i))
answer = [-1]*Q
se = set() # 引っかかってる場所
q.sort()
for a,c,b in q:
if not c:
se.remove(b)
elif c&1:
se.add(b)
else:
if se:
answer[b] = min(se)
print(('\n'.join(map(str,answer))))
| #D in [S_i-X_i,T_i-X_i) → Xiで止まる
import sys
input = sys.stdin.readline
N,Q = list(map(int,input().split()))
q = []
STX = [[int(x) for x in input().split()] for _ in range(N)]
for s,t,x in STX:
q.append((s-x,1,x)) # xで死ぬ
q.append((t-x,0,x)) # xで死ななくなる
for i in range(Q):
d = int(eval(input()))
q.append((d,2,i))
answer = [-1]*Q
se = set() # 引っかかってる場所
q.sort()
min_se = 10**18
flag = False # min_seが正しい
for a,c,b in q:
if not c:
se.remove(b)
if min_se == b:
flag = False
elif c&1:
se.add(b)
if b < min_se:
min_se = b
flag = True
else:
if se:
if not flag:
min_se = min(se)
flag = True
answer[b] = min_se
print(('\n'.join(map(str,answer))))
| p03033 |
#D in [S_i-X_i,T_i-X_i) → Xiで止まる
import sys
input = sys.stdin.readline
from heapq import heappop,heappush
from collections import defaultdict
N,Q = list(map(int,input().split()))
task = []
STX = [[int(x) for x in input().split()] for _ in range(N)]
for s,t,x in STX:
task.append((t-x,0,x)) # xで止まらなくなる
task.append((s-x,1,x)) # xで止まる
for i in range(Q):
d = int(eval(input()))
task.append((d,2,i)) # 止まる位置を答える
answer = [-1]*Q
task.sort()
# 引っかかってる場所の管理
se = [] # heapでソートを保つ
added = defaultdict(int) # 入ってる個数
# 小さい時刻から順に見ていく
for a,b,c in task:
if not b: # b == 0
added[c] -= 1
elif b&1: # b == 1
heappush(se,c)
added[c] += 1
else: # b == 2
while se and added[se[0]] == 0:
heappop(se)
answer[c] = se[0] if se else -1
print(('\n'.join(map(str,answer))))
| #D in [S_i-X_i,T_i-X_i) → Xiで止まる
import sys
input = sys.stdin.readline
from heapq import heappop,heappush
from collections import defaultdict
N,Q = list(map(int,input().split()))
task = []
STX = [[int(x) for x in input().split()] for _ in range(N)]
for s,t,x in STX:
task.append((t-x,0,x)) # xで止まらなくなる
task.append((s-x,1,x)) # xで止まる
for i in range(Q):
d = int(eval(input()))
task.append((d,2,i)) # 止まる位置を答える
answer = [-1]*Q
task.sort()
# 引っかかってる場所の管理
se = set()
se_hp = [] # heapでソートを保つ
# 小さい時刻から順に見ていく
for a,b,c in task:
if not b: # b == 0
se.remove(c)
elif b&1: # b == 1
se.add(c)
heappush(se_hp,c)
else: # b == 2
while se_hp and se_hp[0] not in se:
heappop(se_hp)
answer[c] = se_hp[0] if se_hp else -1
print(('\n'.join(map(str,answer))))
| p03033 |
#D in [S_i-X_i,T_i-X_i) → Xiで止まる
import sys
input = sys.stdin.readline
from heapq import heappop,heappush
from collections import defaultdict
N,Q = list(map(int,input().split()))
task = []
STX = [[int(x) for x in input().split()] for _ in range(N)]
for s,t,x in STX:
task.append((t-x,0,x)) # xで止まらなくなる
task.append((s-x,1,x)) # xで止まる
for i in range(Q):
d = int(eval(input()))
task.append((d,2,i)) # 止まる位置を答える
answer = [-1]*Q
task.sort()
# 引っかかってる場所の管理
se = set()
se_hp = [] # heapでソートを保つ
# 小さい時刻から順に見ていく
for a,b,c in task:
if not b: # b == 0
se.remove(c)
elif b&1: # b == 1
se.add(c)
heappush(se_hp,c)
else: # b == 2
while se_hp and se_hp[0] not in se:
heappop(se_hp)
answer[c] = se_hp[0] if se_hp else -1
print(('\n'.join(map(str,answer))))
| #D in [S_i-X_i,T_i-X_i) → Xiで止まる
import sys
input = sys.stdin.readline
from heapq import heappop,heappush
from collections import defaultdict
N,Q = list(map(int,input().split()))
task = []
STX = [[int(x) for x in input().split()] for _ in range(N)]
for s,t,x in STX:
task.append((t-x,0,x)) # xで止まらなくなる
task.append((s-x,1,x)) # xで止まる
for i in range(Q):
d = int(eval(input()))
task.append((d,2,i)) # 止まる位置を答える
answer = [-1]*Q
task.sort()
# 引っかかってる場所の管理
se = set()
se_hp = [] # heapで最小値を先頭に保つ
# 小さい時刻から順に見ていく
for a,b,c in task:
if not b: # b == 0
se.remove(c)
elif b&1: # b == 1
se.add(c)
heappush(se_hp,c)
else: # b == 2
while se_hp and se_hp[0] not in se:
heappop(se_hp)
answer[c] = se_hp[0] if se_hp else -1
print(('\n'.join(map(str,answer))))
| p03033 |
#D in [S_i-X_i,T_i-X_i) → Xiで止まる
import sys
input = sys.stdin.readline
from heapq import heappop,heappush
from collections import defaultdict
N,Q = list(map(int,input().split()))
task = []
STX = [[int(x) for x in input().split()] for _ in range(N)]
for s,t,x in STX:
task.append((t-x,0,x)) # xで止まらなくなる
task.append((s-x,1,x)) # xで止まる
for i in range(Q):
d = int(eval(input()))
task.append((d,2,i)) # 止まる位置を答える
answer = [-1]*Q
task.sort()
# 引っかかってる場所の管理
se = set()
se_hp = [] # heapで最小値を先頭に保つ
# 小さい時刻から順に見ていく
for a,b,c in task:
if not b: # b == 0
se.remove(c)
elif b&1: # b == 1
se.add(c)
heappush(se_hp,c)
else: # b == 2
while se_hp and se_hp[0] not in se:
heappop(se_hp)
answer[c] = se_hp[0] if se_hp else -1
print(('\n'.join(map(str,answer))))
| import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from heapq import heappush, heappop
from collections import defaultdict
N,Q = list(map(int,readline().split()))
data = list(map(int,read().split()))
S = data[:3*N:3]
T = data[1:3*N:3]
X = data[2:3*N:3]
D = data[3*N:]
event = []
event += [(s-x,1,x) for x,s in zip(X,S)] # xに通行止めを1つ追加
event += [(t-x,2,x) for x,t in zip(X,T)] # xの通行止めを1つ削除
event += [(x,3,i) for i,x in enumerate(D)] # 最小の通行止めを答える
event.sort()
INF = 10**10
q = [INF]
counter = defaultdict(int)
counter[INF] = 1
answer = [None] * Q
for a,b,c in event:
if b == 1:
heappush(q,c)
counter[c] += 1
elif b == 2:
counter[c] -= 1
else:
while counter[q[0]] == 0:
heappop(q)
x = q[0]
if x == INF:
x = -1
answer[c] = x
print(('\n'.join(map(str,answer)))) | p03033 |
#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
import collections
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from builtins import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
else:
_str = str
str = lambda x=b"": x if type(x) is bytes else _str(x).encode()
def main():
N, Q = [int(x) for x in input().split()]
updates = []
for i in range(N):
S, T, X = [int(x) for x in input().split()]
updates.append((S - X, 1, X))
updates.append((T - X, -1, X))
active = []
to_delete = collections.defaultdict(int)
import heapq
heapq.heapify(updates)
for _ in range(Q):
x = int(eval(input()))
while updates and updates[0][0] <= x:
coord, tp, val = heapq.heappop(updates)
if tp == -1:
to_delete[val] += 1
else:
heapq.heappush(active, val)
while active and to_delete[active[0]] > 0:
to_delete[active[0]] -= 1
heapq.heappop(active)
print(active[0] if active else -1)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._buffer = BytesIO()
self._fd = file.fileno()
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):
if self._buffer.tell():
return self._buffer.read()
return os.read(self._fd, os.fstat(self._fd).st_size)
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)
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", b"\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")
# endregion
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
import collections
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from builtins import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
else:
_str = str
str = lambda x=b"": x if type(x) is bytes else _str(x).encode()
def main():
N, Q = [int(x) for x in input().split()]
add, delete = [], []
for i in range(N):
S, T, X = [int(x) for x in input().split()]
add.append((S - X, X))
delete.append((T - X, X))
active = []
to_delete = collections.defaultdict(int)
import heapq
heapq.heapify(add)
heapq.heapify(delete)
for _ in range(Q):
x = int(eval(input()))
while add and add[0][0] <= x:
coord, val = heapq.heappop(add)
heapq.heappush(active, val)
while delete and delete[0][0] <= x:
coord, val = heapq.heappop(delete)
to_delete[val] += 1
while active and to_delete[active[0]] > 0:
to_delete[active[0]] -= 1
heapq.heappop(active)
print(active[0] if active else -1)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._buffer = BytesIO()
self._fd = file.fileno()
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):
if self._buffer.tell():
return self._buffer.read()
return os.read(self._fd, os.fstat(self._fd).st_size)
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)
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", b"\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")
# endregion
if __name__ == "__main__":
main()
| p03033 |
#13:12
n,q = list(map(int,input().split()))
import heapq
import sys
input = sys.stdin.readline
event = []
for _ in range(n):
s,t,x = list(map(int,input().split()))
heapq.heappush(event,[s-x,t-x,x])
t = 0
now = []
for _ in range(q):
d = int(eval(input()))
if event:
while event[0][0] <= d:
tmp = heapq.heappop(event)
heapq.heappush(now,[tmp[2],tmp[1]])
if not event:
break
if now:
while now[0][1] <= d:
heapq.heappop(now)
if not now:
print((-1))
break
else:
print((now[0][0]))
else:
print((-1)) | #13:12
n,q = list(map(int,input().split()))
import heapq
import sys
input = sys.stdin.readline
event = []
for _ in range(n):
s,t,x = list(map(int,input().split()))
heapq.heappush(event,(s-x,t-x,x))
t = 0
now = []
for _ in range(q):
d = int(eval(input()))
if event:
while event[0][0] <= d:
tmp = heapq.heappop(event)
heapq.heappush(now,(tmp[2],tmp[1]))
if not event:
break
if now:
while now[0][1] <= d:
heapq.heappop(now)
if not now:
print((-1))
break
else:
print((now[0][0]))
else:
print((-1)) | p03033 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 15 16:58:00 2019
@author: YudNK
"""
import bisect as bs
N, Q = map(int, input().split())
E = []
for i in range(N):
s, t, x = map(int, input().split())
a = [s - x, t - x, x] #イベント
E.append(a)
E.sort(key = lambda x: x[2])
D = []
for i in range(Q):
D.append(int(input()))
ans = [-1]*Q
for e in E:
l = bs.bisect_left(D, e[0])
r = bs.bisect_left(D, e[1])
for i in range(l, r):
if ans[i] == -1:
ans[i] = e[2]
else:
pass
[print(i) for i in ans]
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 15 16:58:00 2019
@author: YudNK
"""
import bisect as bs
N, Q = map(int, input().split())
E = []
for i in range(N):
s, t, x = map(int, input().split())
a = [s - x, t - x, x] #イベント
E.append(a)
E.sort(key = lambda x: x[2])
D = []
for i in range(Q):
D.append(int(input()))
ans = [-1]*Q
check = [-1]*Q
for e in E:
l = bs.bisect_left(D, e[0])
r = bs.bisect_left(D, e[1])
while l < r:
if check[l] == -1:
ans[l] = e[2]
check[l] = r
l += 1
else:
l = check[l]
[print(i) for i in ans]
| p03033 |
N, Q = list(map(int, input().split()))
X = [list(map(int, input().split())) for _ in range(N)]
X.sort(key = lambda x: x[2])
X.append([-1, 1, X[-1][2] + 1])
def quitConst(t):
nextx = [x for x in X if x[1] > t + x[2] or x[0] == -1]
return nextx
def startConst(t):
nextx = [x for x in X if x[0] <= t + x[2] or x[0] == -1]
return nextx
for _ in range(Q):
current = 0
start = int(eval(input()))
X = quitConst(start)
XX = startConst(start)
for x in XX:
current = x[2]
if x[0] <= current + start < x[1]:
break
if current == XX[-1][2]:
print((-1))
else:
print(current) | from bisect import bisect_left as bl
N, Q = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(N)]
X.sort(key = lambda x: x[2])
Y = [int(input()) for _ in range(Q)]
res = [-1] * Q
jump = [-1] * Q
for s,t,x in X:
l=bl(Y,s - x)
r=bl(Y,t - x)
while l < r:
s = jump[l]
if s == -1:
res[l] = x
jump[l] = r
l += 1
else:
l = s
print(*res,sep = '\n')
| p03033 |
if __name__ == '__main__':
N,Q=list(map(int,input().split()))
events=[list(map(int,input().split())) for _ in range(N)]
D=[int(eval(input())) for i in range(Q)]
ans=[-1]*Q
skip=[-1]*Q
events.sort(key=lambda x:x[2])
import bisect
for S,T,X in events:
right=bisect.bisect_left(D,T-X)
left=bisect.bisect_left(D,S-X)
while left<right:
if skip[left]==-1:
ans[left]=X
skip[left]=right
left+=1
else:
left=skip[left]
for i in ans:
print(i)
| import bisect
import sys
input = sys.stdin.readline
n, q = list(map(int, input().split()))
events = [list(map(int, input().split())) for _ in range(n)]
events.sort(key=lambda x: x[2])
departures = [int(eval(input())) for _ in range(q)]
ans = ['-1'] * q
skip = [-1] * q
for start, end, pos in events:
left = bisect.bisect_left(departures, start-pos)
right = bisect.bisect_left(departures, end-pos)
while left < right:
if skip[left] == -1:
ans[left] = str(pos)
skip[left] = right
left += 1
else:
left = skip[left]
print(('\n'.join(ans)))
| p03033 |
if __name__ == '__main__':
N,Q=list(map(int,input().split()))
events=[list(map(int,input().split())) for _ in range(N)]
D=[int(eval(input())) for i in range(Q)]
ans=["-1"]*Q
skip=[-1]*Q
events.sort(key=lambda x:x[2])
import bisect
for S,T,X in events:
right=bisect.bisect_left(D,T-X)
left=bisect.bisect_left(D,S-X)
while left<right:
if skip[left]==-1:
ans[left]=str(X)
skip[left]=right
left+=1
else:
left=skip[left]
print(("\n".join(ans)))
| if __name__ == '__main__':
import sys
input=sys.stdin.readline
N,Q=list(map(int,input().split()))
events=[list(map(int,input().split())) for _ in range(N)]
D=[int(eval(input())) for i in range(Q)]
ans=["-1"]*Q
skip=[-1]*Q
events.sort(key=lambda x:x[2])
import bisect
for S,T,X in events:
right=bisect.bisect_left(D,T-X)
left=bisect.bisect_left(D,S-X)
while left<right:
if skip[left]==-1:
ans[left]=str(X)
skip[left]=right
left+=1
else:
left=skip[left]
print(("\n".join(ans)))
| p03033 |
from bisect import bisect_left, bisect_right
from operator import itemgetter
import sys
input = sys.stdin.readline
INF = float("inf")
def main():
N, Q = list(map(int, input().split()))
constructions = [None] * N
for i in range(N):
S, T, X = list(map(int, input().split()))
constructions[i] = (S, T, X)
D = [int(eval(input())) for _ in range(Q)]
ans = [INF] * Q
for S, T, X in constructions:
l = bisect_left(D, S-X)
r = bisect_right(D, T-X-1)
for idx in range(l, r):
ans[idx] = min(X, ans[idx])
for a in ans:
if a == INF:
print((-1))
else:
print(a)
if __name__ == "__main__":
main()
| from bisect import bisect_left, bisect_right
from operator import itemgetter
import sys
input = sys.stdin.readline
def main():
N, Q = list(map(int, input().split()))
constructions = [None] * N
for i in range(N):
S, T, X = list(map(int, input().split()))
constructions[i] = (S, T, X)
constructions.sort(key=itemgetter(2))
D = [int(eval(input())) for _ in range(Q)]
ans = [-1] * Q
nxt = list(range(1, Q+1))
for S, T, X in constructions:
l = bisect_left(D, S-X)
r = bisect_right(D, T-X-1)
idx = l
while idx < r:
if ans[idx] == -1:
ans[idx] = X
nidx = nxt[idx]
nxt[idx] = max(nxt[idx], r)
idx = nidx
for a in ans:
print(a)
if __name__ == "__main__":
main()
| p03033 |
import sys
input=sys.stdin.readline
from collections import deque
from heapq import heappush,heappop
import re
def int_raw():
return int(eval(input()))
def ss_raw():
return input().split()
def ints_raw():
return tuple(map(int, ss_raw()))
def main():
N ,Q = ints_raw()
origST = []
for idx in range(N):
S,T,X = ints_raw()
origST.append([S-X,1,X])
origST.append([T-X,-1,X])
origST.sort()
stidx = 0
cur_set = set([])
for idx in range(Q):
q = int_raw()
while stidx < len(origST):
st = origST[stidx]
if st[0] > q:
break
if st[1]>0:
cur_set.add(st[2])
else:
cur_set.remove(st[2])
stidx+=1
if len(cur_set)==0:
print((-1))
else:
print((min(cur_set)))
main()
| import sys
input=sys.stdin.readline
from collections import deque
from heapq import heappush,heappop
import re
def int_raw():
return int(eval(input()))
def ss_raw():
return input().split()
def ints_raw():
return tuple(map(int, ss_raw()))
def main():
N ,Q = ints_raw()
origST = []
for idx in range(N):
S,T,X = ints_raw()
origST.append([S-X,T-X,X])
Ds = [int(eval(input())) for _ in range(Q)]
origST.sort()
stidx = 0
cur_set = []
for q in Ds:
while stidx < len(origST):
st = origST[stidx]
if st[0] > q:
break
heappush(cur_set,(st[2],st[1]))
stidx+=1
while cur_set and cur_set[0][1] <=q:
heappop(cur_set)
if len(cur_set)==0:
print((-1))
else:
print((cur_set[0][0]))
main()
| p03033 |
from heapq import heappush,heappop
n,q=list(map(int,input().split()))
e=[]
for i in range(n):
s,t,x=list(map(int,input().split()))
e.append((s-x,1,x))
e.append((t-x,-1,x))
for i in range(q):
d=int(eval(input()))
e.append((d,2,0))
e.sort()
s=set()
a=[]
for time_,type_,x_ in e:
if type_==1:
s.add(x_)
heappush(a,x_)
elif type_==-1:
s.remove(x_)
else:
while a and a[0] not in s:
heappop(a)
if a:
print((a[0]))
else:
print((-1)) | import sys
from heapq import heappush,heappop
input=sys.stdin.readline
n,q=list(map(int,input().split()))
e=[]
for i in range(n):
s,t,x=list(map(int,input().split()))
e.append((s-x,1,x))
e.append((t-x,-1,x))
for i in range(q):
d=int(eval(input()))
e.append((d,2,0))
e.sort()
s=set()
a=[]
for time_,type_,x_ in e:
if type_==1:
s.add(x_)
heappush(a,x_)
elif type_==-1:
s.remove(x_)
else:
while a and a[0] not in s:
heappop(a)
if a:
print((a[0]))
else:
print((-1)) | p03033 |
import sys
input = sys.stdin.readline
def main():
n, q = list(map(int, input().split()))
V = []
for i in range(n):
s, t, x = list(map(int, input().split()))
V.append((s-x, x, 1)) #1: insert
V.append((t-x, x, 0)) #0: delete
D = []
for i in range(q):
d = int(eval(input()))
V.append((d, i, 2)) #2: query
V.sort(key=lambda x:(x[0], x[2]))
se = set()
hq = []
import heapq
heapq.heapify(hq)
ans = [-1]*q
for t, v, p in V:
if p == 1:
se.add(v)
heapq.heappush(hq, v)
elif p == 0:
se.discard(v)
else:
while hq and hq[0] not in se:
heapq.heappop(hq)
if hq:
ans[v] = hq[0]
for i in range(q):
print((ans[i]))
if __name__ == '__main__':
main() | import sys
input = sys.stdin.readline
def main():
n, q = list(map(int, input().split()))
V = []
for i in range(n):
s, t, x = list(map(int, input().split()))
V.append((s-x, x, 1)) #1: insert
V.append((t-x, x, 0)) #0: delete
D = []
for i in range(q):
d = int(eval(input()))
V.append((d, i, 2)) #2: query
V.sort(key=lambda x:(x[0], x[2]))
se = set()
hq = []
import heapq
heapq.heapify(hq)
ans = [-1]*q
for t, v, p in V:
if p == 1:
se.add(v)
heapq.heappush(hq, v)
elif p == 0:
se.remove(v)
else:
while hq and hq[0] not in se:
heapq.heappop(hq)
if hq:
ans[v] = hq[0]
for i in range(q):
print((ans[i]))
if __name__ == '__main__':
main() | p03033 |
from bisect import bisect_left, bisect_right
class LazySegmentTree:
INF = float("inf")
def __init__(self, n):
self.n = 1 << (n-1).bit_length()
self.data = [self.INF] * (self.n*2)
self.lazy = [None] * (self.n*2)
def build(self, data):
for i, x in enumerate(data):
self.data[self.n+i] = x
for i in range(self.n-1, 0, -1):
self.data[i] = min(self.data[i*2], self.data[i*2+1])
def query(self, l, r):
if not l < r: return self.INF
self.__propagate(self.__getidx(l, r))
l += self.n; r += self.n
res = self.INF
while l < r:
if l & 1:
res = min(res, self.data[l])
l += 1
if r & 1:
res = min(res, self.data[r-1])
l >>= 1; r >>= 1
return res
def update(self, l, r, x):
if not l < r: return
idx = self.__getidx(l, r)
self.__propagate(idx)
l += self.n; r += self.n
while l < r:
if l & 1:
self.data[l], self.lazy[l] = x, x
l += 1
if r & 1:
self.data[r-1], self.lazy[r-1] = x, x
l >>= 1; r >>= 1
for i in idx:
self.data[i] = min(self.data[i*2], self.data[i*2+1])
def __getidx(self, l, r):
l += self.n; r += self.n
lm = l // ((l & -l) << 1)
rm = r // ((r & -r) << 1)
res = []
while l < r:
if l <= lm: res.append(l)
if r <= rm: res.append(r)
l >>= 1; r >>= 1
while l:
res.append(l)
l >>= 1
return res
def __propagate(self, idx):
for i in reversed(idx):
val = self.lazy[i]
if val is None: continue
self.lazy[i*2] = val; self.lazy[i*2+1] = val
self.data[i*2] = val; self.data[i*2+1] = val
self.lazy[i] = None
n, q = list(map(int, input().split()))
query = [None] * n
for i in range(n):
s, t, x = list(map(int, input().split()))
query[i] = s-x, t-x, x
d = [int(eval(input())) for _ in range(q)]
lst = LazySegmentTree(q)
query.sort(key=lambda x: x[2], reverse=True)
for l, r, x in query:
lst.update(bisect_left(d, l), bisect_left(d, r), x)
for i in range(q):
ans = lst.query(i, i+1)
print((-1 if ans == float("inf") else ans))
| import sys
input = lambda: sys.stdin.readline()
from bisect import bisect_left, bisect_right
class LazySegmentTree:
INF = float("inf")
def __init__(self, n):
self.n = 1 << (n-1).bit_length()
self.data = [self.INF] * (self.n*2)
self.lazy = [None] * (self.n*2)
def build(self, data):
for i, x in enumerate(data):
self.data[self.n+i] = x
for i in range(self.n-1, 0, -1):
self.data[i] = min(self.data[i*2], self.data[i*2+1])
def query(self, l, r):
if not l < r: return self.INF
self.__propagate(self.__getidx(l, r))
l += self.n; r += self.n
res = self.INF
while l < r:
if l & 1:
res = min(res, self.data[l])
l += 1
if r & 1:
res = min(res, self.data[r-1])
l >>= 1; r >>= 1
return res
def update(self, l, r, x):
if not l < r: return
idx = self.__getidx(l, r)
self.__propagate(idx)
l += self.n; r += self.n
while l < r:
if l & 1:
self.data[l], self.lazy[l] = x, x
l += 1
if r & 1:
self.data[r-1], self.lazy[r-1] = x, x
l >>= 1; r >>= 1
for i in idx:
self.data[i] = min(self.data[i*2], self.data[i*2+1])
def __getidx(self, l, r):
l += self.n; r += self.n
lm = l // ((l & -l) << 1)
rm = r // ((r & -r) << 1)
res = []
while l < r:
if l <= lm: res.append(l)
if r <= rm: res.append(r)
l >>= 1; r >>= 1
while l:
res.append(l)
l >>= 1
return res
def __propagate(self, idx):
for i in reversed(idx):
val = self.lazy[i]
if val is None: continue
self.lazy[i*2] = val; self.lazy[i*2+1] = val
self.data[i*2] = val; self.data[i*2+1] = val
self.lazy[i] = None
n, q = list(map(int, input().split()))
query = [None] * n
for i in range(n):
s, t, x = list(map(int, input().split()))
query[i] = s-x, t-x, x
d = [int(eval(input())) for _ in range(q)]
lst = LazySegmentTree(q)
query.sort(key=lambda x: x[2], reverse=True)
for l, r, x in query:
lst.update(bisect_left(d, l), bisect_left(d, r), x)
for i in range(q):
ans = lst.query(i, i+1)
print((-1 if ans == float("inf") else ans))
| p03033 |
import heapq
import sys
sys.setrecursionlimit(10 ** 7)
n,q=list(map(int,input().split()))
event=[]
for _ in range(n):
s,t,x=list(map(int,input().split()))
event.append([s-x,1,x])
event.append([t-x,-1,x])
for i in range(q):
event.append([int(eval(input())),2,i])
event.sort()
ans=[0]*q
stop=set()
hq=[]
for e in event:
t,op,x=[x for x in e]
if op==1:
heapq.heappush(hq,x)
stop.add(x)
elif op==-1:
stop.remove(x)
else:
while hq and hq[0] not in stop:
heapq.heappop(hq)
ans[x]=hq[0] if hq else -1
for x in ans:
print(x) | import heapq
import sys
sys.setrecursionlimit(10 ** 7)
n,q=list(map(int,input().split()))
event=[]
for _ in range(n):
s,t,x=list(map(int,input().split()))
event.append((s-x,1,x))
event.append((t-x,-1,x))
for i in range(q):
event.append((int(eval(input())),2,i))
event.sort()
ans=[0]*q
stop=set()
hq=[]
for t,op,x in event:
if op==1:
heapq.heappush(hq,x)
stop.add(x)
elif op==-1:
stop.remove(x)
else:
while hq and hq[0] not in stop:
heapq.heappop(hq)
ans[x]=hq[0] if hq else -1
for x in ans:
print(x) | p03033 |
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(10 ** 7)
n,q=list(map(int,input().split()))
event=[]
for _ in range(n):
s,t,x=list(map(int,input().split()))
event.append((s-x,1,x))
event.append((t-x,-1,x))
for i in range(q):
event.append((int(eval(input())),2,i))
event.sort()
ans=[0]*q
stop=set()
hq=[]
for t,op,x in event:
if op==1:
heappush(hq,x)
stop.add(x)
elif op==-1:
stop.remove(x)
else:
while hq and hq[0] not in stop:
heappop(hq)
ans[x]=hq[0] if hq else -1
for x in ans:
print(x) | def main():
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(10 ** 7)
n,q=list(map(int,input().split()))
event=[]
for _ in range(n):
s,t,x=list(map(int,input().split()))
event.append((s-x,1,x))
event.append((t-x,-1,x))
for i in range(q):
event.append((int(eval(input())),2,i))
event.sort()
ans=[0]*q
stop=set()
hq=[]
for t,op,x in event:
if op==1:
heappush(hq,x)
stop.add(x)
elif op==-1:
stop.remove(x)
else:
while hq and hq[0] not in stop:
heappop(hq)
ans[x]=hq[0] if hq else -1
for x in ans:
print(x)
main() | p03033 |
def main():
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(10 ** 7)
n,q=list(map(int,input().split()))
event=[]
for _ in range(n):
s,t,x=list(map(int,input().split()))
event.append((s-x,1,x))
event.append((t-x,-1,x))
for i in range(q):
event.append((int(eval(input())),2,i))
event.sort()
ans=[0]*q
stop=set()
hq=[]
for t,op,x in event:
if op==1:
heappush(hq,x)
stop.add(x)
elif op==-1:
stop.remove(x)
else:
while hq and hq[0] not in stop:
heappop(hq)
ans[x]=hq[0] if hq else -1
for x in ans:
print(x)
main() | from heapq import heappush, heappop
import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N, Q = list(map(int, readline().split()))
STX = [[int(x) for x in readline().split()] for _ in range(N)]
EVENT = []
for s, t, x in STX:
EVENT.append((s-x, 1, x))
EVENT.append((t-x, 0, x))
for i in range(Q):
d = int(readline())
EVENT.append((d, 2, i))
ans = [-1] * Q
EVENT.sort()
STOP = set()
h = []
for t, op, x in EVENT:
if op == 2 and STOP:
while h and h[0] not in STOP:
heappop(h)
ans[x] = h[0]
elif op == 1:
STOP.add(x)
heappush(h, x)
elif op == 0:
STOP.remove(x)
print(("\n".join(map(str, ans))))
| p03033 |
def main():
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n,q=list(map(int,readline().split()))
stx = [[int(x) for x in readline().split()] for _ in range(n)]
event=[]
stop=set()
for s,t,x in stx:
event.append([s-x,1,x])
event.append([t-x,-1,x])
for i in range(q):
event.append([int(eval(input())),2,i])
event.sort()
ans=[0]*q
stop=set()
hq=[]
for e in event:
t,op,x=[x for x in e]
if op==1:
heappush(hq,x)
stop.add(x)
elif op==-1:
stop.remove(x)
else:
while hq and hq[0] not in stop:
heappop(hq)
ans[x]=hq[0] if hq else -1
for x in ans:
print(x)
if __name__ == "__main__":
main() | def main():
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n,q=list(map(int,readline().split()))
stx = [[int(x) for x in readline().split()] for _ in range(n)]
event=[]
stop=set()
for s,t,x in stx:
event.append([s-x,1,x])
event.append([t-x,-1,x])
for i in range(q):
event.append([int(eval(input())),2,i])
event.sort()
ans=[0]*q
stop=set()
hq=[]
for t,op,x in event:
if op==1:
heappush(hq,x)
stop.add(x)
elif op==-1:
stop.remove(x)
else:
while hq and hq[0] not in stop:
heappop(hq)
ans[x]=hq[0] if hq else -1
for x in ans:
print(x)
if __name__ == "__main__":
main() | p03033 |
"""Sorted List
==============
:doc:`Sorted Containers<index>` is an Apache2 licensed Python sorted
collections library, written in pure-Python, and fast as C-extensions. The
:doc:`introduction<introduction>` is the best way to get started.
Sorted list implementations:
.. currentmodule:: sortedcontainers
* :class:`SortedList`
* :class:`SortedKeyList`
"""
# pylint: disable=too-many-lines
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
from collections.abc import Sequence, MutableSequence, ItemsView, KeysView, ValuesView, MutableSet, Set
from functools import wraps, reduce
from _thread import get_ident
def recursive_repr(fillvalue='...'):
"Decorator to make a repr function return fillvalue for a recursive call."
# pylint: disable=missing-docstring
# Copied from reprlib in Python 3
# https://hg.python.org/cpython/file/3.6/Lib/reprlib.py
def decorating_function(user_function):
repr_running = set()
@wraps(user_function)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper
return decorating_function
###############################################################################
# END Python 2/3 Shims
###############################################################################
class SortedList(MutableSequence):
"""Sorted list is a sorted mutable sequence.
Sorted list values are maintained in sorted order.
Sorted list values must be comparable. The total ordering of values must
not change while they are stored in the sorted list.
Methods for adding values:
* :func:`SortedList.add`
* :func:`SortedList.update`
* :func:`SortedList.__add__`
* :func:`SortedList.__iadd__`
* :func:`SortedList.__mul__`
* :func:`SortedList.__imul__`
Methods for removing values:
* :func:`SortedList.clear`
* :func:`SortedList.discard`
* :func:`SortedList.remove`
* :func:`SortedList.pop`
* :func:`SortedList.__delitem__`
Methods for looking up values:
* :func:`SortedList.bisect_left`
* :func:`SortedList.bisect_right`
* :func:`SortedList.count`
* :func:`SortedList.index`
* :func:`SortedList.__contains__`
* :func:`SortedList.__getitem__`
Methods for iterating values:
* :func:`SortedList.irange`
* :func:`SortedList.islice`
* :func:`SortedList.__iter__`
* :func:`SortedList.__reversed__`
Methods for miscellany:
* :func:`SortedList.copy`
* :func:`SortedList.__len__`
* :func:`SortedList.__repr__`
* :func:`SortedList._check`
* :func:`SortedList._reset`
Sorted lists use lexicographical ordering semantics when compared to other
sequences.
Some methods of mutable sequences are not supported and will raise
not-implemented error.
"""
DEFAULT_LOAD_FACTOR = 1000
def __init__(self, iterable=None, key=None):
"""Initialize sorted list instance.
Optional `iterable` argument provides an initial iterable of values to
initialize the sorted list.
Runtime complexity: `O(n*log(n))`
>>> sl = SortedList()
>>> sl
SortedList([])
>>> sl = SortedList([3, 1, 2, 5, 4])
>>> sl
SortedList([1, 2, 3, 4, 5])
:param iterable: initial values (optional)
"""
assert key is None
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
"""Create new sorted list or sorted-key list instance.
Optional `key`-function argument will return an instance of subtype
:class:`SortedKeyList`.
>>> sl = SortedList()
>>> isinstance(sl, SortedList)
True
>>> sl = SortedList(key=lambda x: -x)
>>> isinstance(sl, SortedList)
True
>>> isinstance(sl, SortedKeyList)
True
:param iterable: initial values (optional)
:param key: function used to extract comparison key (optional)
:return: sorted list or sorted-key list instance
"""
# pylint: disable=unused-argument
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedKeyList)
else:
raise TypeError('inherit SortedKeyList for key argument')
@property
def key(self): # pylint: disable=useless-return
"""Function used to extract comparison key from values.
Sorted list compares values directly so the key function is none.
"""
return None
def _reset(self, load):
"""Reset sorted list load factor.
The `load` specifies the load-factor of the list. The default load
factor of 1000 works well for lists from tens to tens-of-millions of
values. Good practice is to use a value that is the cube root of the
list size. With billions of elements, the best load factor depends on
your usage. It's best to leave the load factor at the default until you
start benchmarking.
See :doc:`implementation` and :doc:`performance-scale` for more
information.
Runtime complexity: `O(n)`
:param int load: load-factor for sorted list sublists
"""
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._update(values)
def clear(self):
"""Remove all values from sorted list.
Runtime complexity: `O(n)`
"""
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
self._offset = 0
_clear = clear
def add(self, value):
"""Add `value` to sorted list.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList()
>>> sl.add(3)
>>> sl.add(1)
>>> sl.add(2)
>>> sl
SortedList([1, 2, 3])
:param value: value to add to sorted list
"""
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
"""Split sublists with length greater than double the load-factor.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
"""
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
"""Update sorted list by adding all values from `iterable`.
Runtime complexity: `O(k*log(n))` -- approximate.
>>> sl = SortedList()
>>> sl.update([3, 1, 2])
>>> sl
SortedList([1, 2, 3])
:param iterable: iterable of values to add
"""
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list.
``sl.__contains__(value)`` <==> ``value in sl``
Runtime complexity: `O(log(n))`
>>> sl = SortedList([1, 2, 3, 4, 5])
>>> 3 in sl
True
:param value: search for value in sorted list
:return: true if `value` in sorted list
"""
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def discard(self, value):
"""Remove `value` from sorted list if it is a member.
If `value` is not a member, do nothing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([1, 2, 3, 4, 5])
>>> sl.discard(5)
>>> sl.discard(0)
>>> sl == [1, 2, 3, 4]
True
:param value: `value` to discard from sorted list
"""
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member.
If `value` is not a member, raise ValueError.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([1, 2, 3, 4, 5])
>>> sl.remove(5)
>>> sl == [1, 2, 3, 4]
True
>>> sl.remove(0)
Traceback (most recent call last):
...
ValueError: 0 not in list
:param value: `value` to remove from sorted list
:raises ValueError: if `value` is not in sorted list
"""
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
else:
raise ValueError('{0!r} not in list'.format(value))
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`.
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
:param int pos: lists index
:param int idx: sublist index
"""
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
"""Convert an index pair (lists index, sublist index) into a single
index number that corresponds to the position of the value in the
sorted list.
Many queries require the index be built. Details of the index are
described in ``SortedList._build_index``.
Indexing requires traversing the tree from a leaf node to the root. The
parent of each node is easily computable at ``(pos - 1) // 2``.
Left-child nodes are always at odd indices and right-child nodes are
always at even indices.
When traversing up from a right-child node, increment the total by the
left-child node.
The final index is the sum from traversal and the index in the sublist.
For example, using the index from ``SortedList._build_index``::
_index = 14 5 9 3 2 4 5
_offset = 3
Tree::
14
5 9
3 2 4 5
Converting an index pair (2, 3) into a single index involves iterating
like so:
1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify
the node as a left-child node. At such nodes, we simply traverse to
the parent.
2. At node 9, position 2, we recognize the node as a right-child node
and accumulate the left-child in our total. Total is now 5 and we
traverse to the parent at position 0.
3. Iteration ends at the root.
The index is then the sum of the total and sublist index: 5 + 3 = 8.
:param int pos: lists index
:param int idx: sublist index
:return: index in sorted list
"""
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
# Increment pos to point in the index to len(self._lists[pos]).
pos += self._offset
# Iterate until reaching the root of the index tree at pos = 0.
while pos:
# Right-child nodes are at odd indices. At such indices
# account the total below the left child node.
if not pos & 1:
total += _index[pos - 1]
# Advance pos to the parent node.
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
"""Convert an index into an index pair (lists index, sublist index)
that can be used to access the corresponding lists position.
Many queries require the index be built. Details of the index are
described in ``SortedList._build_index``.
Indexing requires traversing the tree to a leaf node. Each node has two
children which are easily computable. Given an index, pos, the
left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 +
2``.
When the index is less than the left-child, traversal moves to the
left sub-tree. Otherwise, the index is decremented by the left-child
and traversal moves to the right sub-tree.
At a child node, the indexing pair is computed from the relative
position of the child node as compared with the offset and the remaining
index.
For example, using the index from ``SortedList._build_index``::
_index = 14 5 9 3 2 4 5
_offset = 3
Tree::
14
5 9
3 2 4 5
Indexing position 8 involves iterating like so:
1. Starting at the root, position 0, 8 is compared with the left-child
node (5) which it is greater than. When greater the index is
decremented and the position is updated to the right child node.
2. At node 9 with index 3, we again compare the index to the left-child
node with value 4. Because the index is the less than the left-child
node, we simply traverse to the left.
3. At node 4 with index 3, we recognize that we are at a leaf node and
stop iterating.
4. To compute the sublist index, we subtract the offset from the index
of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we
simply use the index remaining from iteration. In this case, 3.
The final index pair from our example is (2, 3) which corresponds to
index 8 in the sorted list.
:param int idx: index in sorted list
:return: (lists index, sublist index) pair
"""
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError('list index out of range')
elif idx >= self._len:
raise IndexError('list index out of range')
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
"""Build a positional index for indexing the sorted list.
Indexes are represented as binary trees in a dense array notation
similar to a binary heap.
For example, given a lists representation storing integers::
0: [1, 2, 3]
1: [4, 5]
2: [6, 7, 8, 9]
3: [10, 11, 12, 13, 14]
The first transformation maps the sub-lists by their length. The
first row of the index is the length of the sub-lists::
0: [3, 2, 4, 5]
Each row after that is the sum of consecutive pairs of the previous
row::
1: [5, 9]
2: [14]
Finally, the index is built by concatenating these lists together::
_index = [14, 5, 9, 3, 2, 4, 5]
An offset storing the start of the first row is also stored::
_offset = 3
When built, the index can be used for efficient indexing into the list.
See the comment and notes on ``SortedList._pos`` for details.
"""
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, list(zip(head, tail))))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, list(zip(head, tail))))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
"""Remove value at `index` from sorted list.
``sl.__delitem__(index)`` <==> ``del sl[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> del sl[2]
>>> sl
SortedList(['a', 'b', 'd', 'e'])
>>> del sl[:2]
>>> sl
SortedList(['d', 'e'])
:param index: integer or slice for indexing
:raises IndexError: if index out of range
"""
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = list(range(start, stop, step))
# Delete items from greatest index to least so
# that the indices remain valid throughout iteration.
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
"""Lookup value at `index` in sorted list.
``sl.__getitem__(index)`` <==> ``sl[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> sl[1]
'b'
>>> sl[-1]
'e'
>>> sl[2:5]
['c', 'd', 'e']
:param index: integer or slice for indexing
:return: value or list of values
:raises IndexError: if index out of range
"""
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
# Whole slice optimization: start to stop slices the whole
# sorted list.
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
start_list = _lists[start_pos]
stop_idx = start_idx + stop - start
# Small slice optimization: start index and stop index are
# within the start list.
if len(start_list) >= stop_idx:
return start_list[start_idx:stop_idx]
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1):stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
# Return a list because a negative step could
# reverse the order of the items and this could
# be the desired behavior.
indices = list(range(start, stop, step))
return list(self._getitem(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError('list index out of range')
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
_getitem = __getitem__
def __setitem__(self, index, value):
"""Raise not-implemented error.
``sl.__setitem__(index, value)`` <==> ``sl[index] = value``
:raises NotImplementedError: use ``del sl[index]`` and
``sl.add(value)`` instead
"""
message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
raise NotImplementedError(message)
def __iter__(self):
"""Return an iterator over the sorted list.
``sl.__iter__()`` <==> ``iter(sl)``
Iterating the sorted list while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return chain.from_iterable(self._lists)
def __reversed__(self):
"""Return a reverse iterator over the sorted list.
``sl.__reversed__()`` <==> ``reversed(sl)``
Iterating the sorted list while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return chain.from_iterable(list(map(reversed, reversed(self._lists))))
def reverse(self):
"""Raise not-implemented error.
Sorted list maintains values in ascending sort order. Values may not be
reversed in-place.
Use ``reversed(sl)`` for an iterator over values in descending sort
order.
Implemented to override `MutableSequence.reverse` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``reversed(sl)`` instead
"""
raise NotImplementedError('use ``reversed(sl)`` instead')
def islice(self, start=None, stop=None, reverse=False):
"""Return an iterator that slices sorted list from `start` to `stop`.
The `start` and `stop` index are treated inclusive and exclusive,
respectively.
Both `start` and `stop` default to `None` which is automatically
inclusive of the beginning and end of the sorted list.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> sl = SortedList('abcdefghij')
>>> it = sl.islice(2, 6)
>>> list(it)
['c', 'd', 'e', 'f']
:param int start: start index (inclusive)
:param int stop: stop index (exclusive)
:param bool reverse: yield values in reverse order
:return: iterator
"""
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
"""Return an iterator that slices sorted list using two index pairs.
The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the
first inclusive and the latter exclusive. See `_pos` for details on how
an index is converted to an index pair.
When `reverse` is `True`, values are yielded from the iterator in
reverse order.
"""
_lists = self._lists
if min_pos > max_pos:
return iter(())
if min_pos == max_pos:
if reverse:
indices = reversed(list(range(min_idx, max_idx)))
return list(map(_lists[min_pos].__getitem__, indices))
indices = list(range(min_idx, max_idx))
return list(map(_lists[min_pos].__getitem__, indices))
next_pos = min_pos + 1
if next_pos == max_pos:
if reverse:
min_indices = list(range(min_idx, len(_lists[min_pos])))
max_indices = list(range(max_idx))
return chain(
list(map(_lists[max_pos].__getitem__, reversed(max_indices))),
list(map(_lists[min_pos].__getitem__, reversed(min_indices))),
)
min_indices = list(range(min_idx, len(_lists[min_pos])))
max_indices = list(range(max_idx))
return chain(
list(map(_lists[min_pos].__getitem__, min_indices)),
list(map(_lists[max_pos].__getitem__, max_indices)),
)
if reverse:
min_indices = list(range(min_idx, len(_lists[min_pos])))
sublist_indices = list(range(next_pos, max_pos))
sublists = list(map(_lists.__getitem__, reversed(sublist_indices)))
max_indices = list(range(max_idx))
return chain(
list(map(_lists[max_pos].__getitem__, reversed(max_indices))),
chain.from_iterable(list(map(reversed, sublists))),
list(map(_lists[min_pos].__getitem__, reversed(min_indices))),
)
min_indices = list(range(min_idx, len(_lists[min_pos])))
sublist_indices = list(range(next_pos, max_pos))
sublists = list(map(_lists.__getitem__, sublist_indices))
max_indices = list(range(max_idx))
return chain(
list(map(_lists[min_pos].__getitem__, min_indices)),
chain.from_iterable(sublists),
list(map(_lists[max_pos].__getitem__, max_indices)),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
"""Create an iterator of values between `minimum` and `maximum`.
Both `minimum` and `maximum` default to `None` which is automatically
inclusive of the beginning and end of the sorted list.
The argument `inclusive` is a pair of booleans that indicates whether
the minimum and maximum ought to be included in the range,
respectively. The default is ``(True, True)`` such that the range is
inclusive of both minimum and maximum.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> sl = SortedList('abcdefghij')
>>> it = sl.irange('c', 'f')
>>> list(it)
['c', 'd', 'e', 'f']
:param minimum: minimum value to start iterating
:param maximum: maximum value to stop iterating
:param inclusive: pair of booleans
:param bool reverse: yield values in reverse order
:return: iterator
"""
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
"""Return the size of the sorted list.
``sl.__len__()`` <==> ``len(sl)``
:return: size of sorted list
"""
return self._len
def bisect_left(self, value):
"""Return an index to insert `value` in the sorted list.
If the `value` is already present, the insertion point will be before
(to the left of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([10, 11, 12, 13, 14])
>>> sl.bisect_left(12)
2
:param value: insertion index of value in sorted list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], value)
return self._loc(pos, idx)
def bisect_right(self, value):
"""Return an index to insert `value` in the sorted list.
Similar to `bisect_left`, but if `value` is already present, the
insertion point will be after (to the right of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([10, 11, 12, 13, 14])
>>> sl.bisect_right(12)
3
:param value: insertion index of value in sorted list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], value)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, value):
"""Return number of occurrences of `value` in the sorted list.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
>>> sl.count(3)
3
:param value: value to count in sorted list
:return: count
"""
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
"""Return a shallow copy of the sorted list.
Runtime complexity: `O(n)`
:return: new sorted list
"""
return self.__class__(self)
__copy__ = copy
def append(self, value):
"""Raise not-implemented error.
Implemented to override `MutableSequence.append` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``sl.add(value)`` instead
"""
raise NotImplementedError('use ``sl.add(value)`` instead')
def extend(self, values):
"""Raise not-implemented error.
Implemented to override `MutableSequence.extend` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``sl.update(values)`` instead
"""
raise NotImplementedError('use ``sl.update(values)`` instead')
def insert(self, index, value):
"""Raise not-implemented error.
:raises NotImplementedError: use ``sl.add(value)`` instead
"""
raise NotImplementedError('use ``sl.add(value)`` instead')
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list.
Raise :exc:`IndexError` if the sorted list is empty or index is out of
range.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> sl.pop()
'e'
>>> sl.pop(2)
'c'
>>> sl
SortedList(['a', 'b', 'd'])
:param int index: index of value (default -1)
:return: value
:raises IndexError: if index is out of range
"""
if not self._len:
raise IndexError('pop index out of range')
_lists = self._lists
if index == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if index == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=None, stop=None):
"""Return first index of value in sorted list.
Raise ValueError if `value` is not present.
Index must be between `start` and `stop` for the `value` to be
considered present. The default value, None, for `start` and `stop`
indicate the beginning and end of the sorted list.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> sl.index('d')
3
>>> sl.index('z')
Traceback (most recent call last):
...
ValueError: 'z' is not in list
:param value: value in sorted list
:param int start: start index (default None, start of sorted list)
:param int stop: stop index (default None, end of sorted list)
:return: index of value
:raises ValueError: if value is not present
"""
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(value) - 1
if start <= right:
return start
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
"""Return new sorted list containing all values in both sequences.
``sl.__add__(other)`` <==> ``sl + other``
Values in `other` do not need to be in sorted order.
Runtime complexity: `O(n*log(n))`
>>> sl1 = SortedList('bat')
>>> sl2 = SortedList('cat')
>>> sl1 + sl2
SortedList(['a', 'a', 'b', 'c', 't', 't'])
:param other: other iterable
:return: new sorted list
"""
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
"""Update sorted list with values from `other`.
``sl.__iadd__(other)`` <==> ``sl += other``
Values in `other` do not need to be in sorted order.
Runtime complexity: `O(k*log(n))` -- approximate.
>>> sl = SortedList('bat')
>>> sl += 'cat'
>>> sl
SortedList(['a', 'a', 'b', 'c', 't', 't'])
:param other: other iterable
:return: existing sorted list
"""
self._update(other)
return self
def __mul__(self, num):
"""Return new sorted list with `num` shallow copies of values.
``sl.__mul__(num)`` <==> ``sl * num``
Runtime complexity: `O(n*log(n))`
>>> sl = SortedList('abc')
>>> sl * 3
SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])
:param int num: count of shallow copies
:return: new sorted list
"""
values = reduce(iadd, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
"""Update the sorted list with `num` shallow copies of values.
``sl.__imul__(num)`` <==> ``sl *= num``
Runtime complexity: `O(n*log(n))`
>>> sl = SortedList('abc')
>>> sl *= 3
>>> sl
SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])
:param int num: count of shallow copies
:return: existing sorted list
"""
values = reduce(iadd, self._lists, []) * num
self._clear()
self._update(values)
return self
def __make_cmp(seq_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted list and sequence."
if not isinstance(other, Sequence):
return NotImplemented
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is eq:
return False
if seq_op is ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
seq_op_name = seq_op.__name__
comparer.__name__ = '__{0}__'.format(seq_op_name)
doc_str = """Return true if and only if sorted list is {0} `other`.
``sl.__{1}__(other)`` <==> ``sl {2} other``
Comparisons use lexicographical order as with sequences.
Runtime complexity: `O(n)`
:param other: `other` sequence
:return: true if sorted list is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, '==', 'equal to')
__ne__ = __make_cmp(ne, '!=', 'not equal to')
__lt__ = __make_cmp(lt, '<', 'less than')
__gt__ = __make_cmp(gt, '>', 'greater than')
__le__ = __make_cmp(le, '<=', 'less than or equal to')
__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
__make_cmp = staticmethod(__make_cmp)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values,))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted list.
``sl.__repr__()`` <==> ``repr(sl)``
:return: string representation
"""
return '{0}({1!r})'.format(type(self).__name__, list(self))
def _check(self):
"""Check invariants of sorted list.
Runtime complexity: `O(n)`
"""
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists)
assert self._len == sum(len(sublist) for sublist in self._lists)
# Check all sublists are sorted.
for sublist in self._lists:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
# Check beginning/end of sublists are sorted.
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
# Check _maxes index is the last value of each sublist.
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._lists[pos][-1]
# Check sublist lengths are less than double load-factor.
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
# Check sublist lengths are greater than half load-factor for all
# but the last sublist.
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
# Check index leaf nodes equal length of sublists.
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
# Check index branch nodes are the sum of their children.
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except BaseException:
traceback.print_exc(file=sys.stdout)
print('len', self._len)
print('load', self._load)
print('offset', self._offset)
print('len_index', len(self._index))
print('index', self._index)
print('len_maxes', len(self._maxes))
print('maxes', self._maxes)
print('len_lists', len(self._lists))
print('lists', self._lists)
raise
def identity(value):
"Identity function."
return value
class SortedKeyList(SortedList):
"""Sorted-key list is a subtype of sorted list.
The sorted-key list maintains values in comparison order based on the
result of a key function applied to every value.
All the same methods that are available in :class:`SortedList` are also
available in :class:`SortedKeyList`.
Additional methods provided:
* :attr:`SortedKeyList.key`
* :func:`SortedKeyList.bisect_key_left`
* :func:`SortedKeyList.bisect_key_right`
* :func:`SortedKeyList.irange_key`
Some examples below use:
>>> from operator import neg
>>> neg
<built-in function neg>
>>> neg(1)
-1
"""
def __init__(self, iterable=None, key=identity):
"""Initialize sorted-key list instance.
Optional `iterable` argument provides an initial iterable of values to
initialize the sorted-key list.
Optional `key` argument defines a callable that, like the `key`
argument to Python's `sorted` function, extracts a comparison key from
each value. The default is the identity function.
Runtime complexity: `O(n*log(n))`
>>> from operator import neg
>>> skl = SortedKeyList(key=neg)
>>> skl
SortedKeyList([], key=<built-in function neg>)
>>> skl = SortedKeyList([3, 1, 2], key=neg)
>>> skl
SortedKeyList([3, 2, 1], key=<built-in function neg>)
:param iterable: initial values (optional)
:param key: function used to extract comparison key (optional)
"""
self._key = key
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._keys = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=identity):
return object.__new__(cls)
@property
def key(self):
"Function used to extract comparison key from values."
return self._key
def clear(self):
"""Remove all values from sorted-key list.
Runtime complexity: `O(n)`
"""
self._len = 0
del self._lists[:]
del self._keys[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, value):
"""Add `value` to sorted-key list.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList(key=neg)
>>> skl.add(3)
>>> skl.add(1)
>>> skl.add(2)
>>> skl
SortedKeyList([3, 2, 1], key=<built-in function neg>)
:param value: value to add to sorted-key list
"""
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(value)
if _maxes:
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_keys[pos].append(key)
_maxes[pos] = key
else:
idx = bisect_right(_keys[pos], key)
_lists[pos].insert(idx, value)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
_lists.append([value])
_keys.append([key])
_maxes.append(key)
self._len += 1
def _expand(self, pos):
"""Split sublists with length greater than double the load-factor.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
"""
_lists = self._lists
_keys = self._keys
_index = self._index
if len(_keys[pos]) > (self._load << 1):
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
_keys_pos = _keys[pos]
half = _lists_pos[_load:]
half_keys = _keys_pos[_load:]
del _lists_pos[_load:]
del _keys_pos[_load:]
_maxes[pos] = _keys_pos[-1]
_lists.insert(pos + 1, half)
_keys.insert(pos + 1, half_keys)
_maxes.insert(pos + 1, half_keys[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
"""Update sorted-key list by adding all values from `iterable`.
Runtime complexity: `O(k*log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList(key=neg)
>>> skl.update([3, 1, 2])
>>> skl
SortedKeyList([3, 2, 1], key=<built-in function neg>)
:param iterable: iterable of values to add
"""
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort(key=self._key)
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_keys.extend(list(map(self._key, _list)) for _list in _lists)
_maxes.extend(sublist[-1] for sublist in _keys)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
"""Return true if `value` is an element of the sorted-key list.
``skl.__contains__(value)`` <==> ``value in skl``
Runtime complexity: `O(log(n))`
>>> from operator import neg
>>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)
>>> 3 in skl
True
:param value: search for value in sorted-key list
:return: true if `value` in sorted-key list
"""
_maxes = self._maxes
if not _maxes:
return False
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return False
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return False
if _lists[pos][idx] == value:
return True
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return False
len_sublist = len(_keys[pos])
idx = 0
def discard(self, value):
"""Remove `value` from sorted-key list if it is a member.
If `value` is not a member, do nothing.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.discard(1)
>>> skl.discard(0)
>>> skl == [5, 4, 3, 2]
True
:param value: `value` to discard from sorted-key list
"""
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
def remove(self, value):
"""Remove `value` from sorted-key list; `value` must be a member.
If `value` is not a member, raise ValueError.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)
>>> skl.remove(5)
>>> skl == [4, 3, 2, 1]
True
>>> skl.remove(0)
Traceback (most recent call last):
...
ValueError: 0 not in list
:param value: `value` to remove from sorted-key list
:raises ValueError: if `value` is not in sorted-key list
"""
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} not in list'.format(value))
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`.
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
:param int pos: lists index
:param int idx: sublist index
"""
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_index = self._index
keys_pos = _keys[pos]
lists_pos = _lists[pos]
del keys_pos[idx]
del lists_pos[idx]
self._len -= 1
len_keys_pos = len(keys_pos)
if len_keys_pos > (self._load >> 1):
_maxes[pos] = keys_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_keys) > 1:
if not pos:
pos += 1
prev = pos - 1
_keys[prev].extend(_keys[pos])
_lists[prev].extend(_lists[pos])
_maxes[prev] = _keys[prev][-1]
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_keys_pos:
_maxes[pos] = keys_pos[-1]
else:
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
"""Create an iterator of values between `minimum` and `maximum`.
Both `minimum` and `maximum` default to `None` which is automatically
inclusive of the beginning and end of the sorted-key list.
The argument `inclusive` is a pair of booleans that indicates whether
the minimum and maximum ought to be included in the range,
respectively. The default is ``(True, True)`` such that the range is
inclusive of both minimum and maximum.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> from operator import neg
>>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)
>>> it = skl.irange(14.5, 11.5)
>>> list(it)
[14, 13, 12]
:param minimum: minimum value to start iterating
:param maximum: maximum value to stop iterating
:param inclusive: pair of booleans
:param bool reverse: yield values in reverse order
:return: iterator
"""
min_key = self._key(minimum) if minimum is not None else None
max_key = self._key(maximum) if maximum is not None else None
return self._irange_key(
min_key=min_key, max_key=max_key,
inclusive=inclusive, reverse=reverse,
)
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),
reverse=False):
"""Create an iterator of values between `min_key` and `max_key`.
Both `min_key` and `max_key` default to `None` which is automatically
inclusive of the beginning and end of the sorted-key list.
The argument `inclusive` is a pair of booleans that indicates whether
the minimum and maximum ought to be included in the range,
respectively. The default is ``(True, True)`` such that the range is
inclusive of both minimum and maximum.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> from operator import neg
>>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)
>>> it = skl.irange_key(-14, -12)
>>> list(it)
[14, 13, 12]
:param min_key: minimum key to start iterating
:param max_key: maximum key to stop iterating
:param inclusive: pair of booleans
:param bool reverse: yield values in reverse order
:return: iterator
"""
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
_irange_key = irange_key
def bisect_left(self, value):
"""Return an index to insert `value` in the sorted-key list.
If the `value` is already present, the insertion point will be before
(to the left of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.bisect_left(1)
4
:param value: insertion index of value in sorted-key list
:return: index
"""
return self._bisect_key_left(self._key(value))
def bisect_right(self, value):
"""Return an index to insert `value` in the sorted-key list.
Similar to `bisect_left`, but if `value` is already present, the
insertion point will be after (to the right of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
>>> skl.bisect_right(1)
5
:param value: insertion index of value in sorted-key list
:return: index
"""
return self._bisect_key_right(self._key(value))
bisect = bisect_right
def bisect_key_left(self, key):
"""Return an index to insert `key` in the sorted-key list.
If the `key` is already present, the insertion point will be before (to
the left of) any existing keys.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.bisect_key_left(-1)
4
:param key: insertion index of key in sorted-key list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._keys[pos], key)
return self._loc(pos, idx)
_bisect_key_left = bisect_key_left
def bisect_key_right(self, key):
"""Return an index to insert `key` in the sorted-key list.
Similar to `bisect_key_left`, but if `key` is already present, the
insertion point will be after (to the right of) any existing keys.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
>>> skl.bisect_key_right(-1)
5
:param key: insertion index of key in sorted-key list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._keys[pos], key)
return self._loc(pos, idx)
bisect_key = bisect_key_right
_bisect_key_right = bisect_key_right
def count(self, value):
"""Return number of occurrences of `value` in the sorted-key list.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([4, 4, 4, 4, 3, 3, 3, 2, 2, 1], key=neg)
>>> skl.count(2)
2
:param value: value to count in sorted-key list
:return: count
"""
_maxes = self._maxes
if not _maxes:
return 0
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return 0
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
total = 0
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return total
if _lists[pos][idx] == value:
total += 1
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return total
len_sublist = len(_keys[pos])
idx = 0
def copy(self):
"""Return a shallow copy of the sorted-key list.
Runtime complexity: `O(n)`
:return: new sorted-key list
"""
return self.__class__(self, key=self._key)
__copy__ = copy
def index(self, value, start=None, stop=None):
"""Return first index of value in sorted-key list.
Raise ValueError if `value` is not present.
Index must be between `start` and `stop` for the `value` to be
considered present. The default value, None, for `start` and `stop`
indicate the beginning and end of the sorted-key list.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.index(2)
3
>>> skl.index(0)
Traceback (most recent call last):
...
ValueError: 0 is not in list
:param value: value in sorted-key list
:param int start: start index (default None, start of sorted-key list)
:param int stop: stop index (default None, end of sorted-key list)
:return: index of value
:raises ValueError: if value is not present
"""
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} is not in list'.format(value))
if _lists[pos][idx] == value:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} is not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
"""Return new sorted-key list containing all values in both sequences.
``skl.__add__(other)`` <==> ``skl + other``
Values in `other` do not need to be in sorted-key order.
Runtime complexity: `O(n*log(n))`
>>> from operator import neg
>>> skl1 = SortedKeyList([5, 4, 3], key=neg)
>>> skl2 = SortedKeyList([2, 1, 0], key=neg)
>>> skl1 + skl2
SortedKeyList([5, 4, 3, 2, 1, 0], key=<built-in function neg>)
:param other: other iterable
:return: new sorted-key list
"""
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values, key=self._key)
__radd__ = __add__
def __mul__(self, num):
"""Return new sorted-key list with `num` shallow copies of values.
``skl.__mul__(num)`` <==> ``skl * num``
Runtime complexity: `O(n*log(n))`
>>> from operator import neg
>>> skl = SortedKeyList([3, 2, 1], key=neg)
>>> skl * 2
SortedKeyList([3, 3, 2, 2, 1, 1], key=<built-in function neg>)
:param int num: count of shallow copies
:return: new sorted-key list
"""
values = reduce(iadd, self._lists, []) * num
return self.__class__(values, key=self._key)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values, self.key))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted-key list.
``skl.__repr__()`` <==> ``repr(skl)``
:return: string representation
"""
type_name = type(self).__name__
return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key)
def _check(self):
"""Check invariants of sorted-key list.
Runtime complexity: `O(n)`
"""
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists) == len(self._keys)
assert self._len == sum(len(sublist) for sublist in self._lists)
# Check all sublists are sorted.
for sublist in self._keys:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
# Check beginning/end of sublists are sorted.
for pos in range(1, len(self._keys)):
assert self._keys[pos - 1][-1] <= self._keys[pos][0]
# Check _keys matches _key mapped to _lists.
for val_sublist, key_sublist in zip(self._lists, self._keys):
assert len(val_sublist) == len(key_sublist)
for val, key in zip(val_sublist, key_sublist):
assert self._key(val) == key
# Check _maxes index is the last value of each sublist.
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._keys[pos][-1]
# Check sublist lengths are less than double load-factor.
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
# Check sublist lengths are greater than half load-factor for all
# but the last sublist.
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
# Check index leaf nodes equal length of sublists.
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
# Check index branch nodes are the sum of their children.
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except BaseException:
traceback.print_exc(file=sys.stdout)
print('len', self._len)
print('load', self._load)
print('offset', self._offset)
print('len_index', len(self._index))
print('index', self._index)
print('len_maxes', len(self._maxes))
print('maxes', self._maxes)
print('len_keys', len(self._keys))
print('keys', self._keys)
print('len_lists', len(self._lists))
print('lists', self._lists)
raise
class SortedSet(MutableSet, Sequence):
"""Sorted set is a sorted mutable set.
Sorted set values are maintained in sorted order. The design of sorted set
is simple: sorted set uses a set for set-operations and maintains a sorted
list of values.
Sorted set values must be hashable and comparable. The hash and total
ordering of values must not change while they are stored in the sorted set.
Mutable set methods:
* :func:`SortedSet.__contains__`
* :func:`SortedSet.__iter__`
* :func:`SortedSet.__len__`
* :func:`SortedSet.add`
* :func:`SortedSet.discard`
Sequence methods:
* :func:`SortedSet.__getitem__`
* :func:`SortedSet.__delitem__`
* :func:`SortedSet.__reversed__`
Methods for removing values:
* :func:`SortedSet.clear`
* :func:`SortedSet.pop`
* :func:`SortedSet.remove`
Set-operation methods:
* :func:`SortedSet.difference`
* :func:`SortedSet.difference_update`
* :func:`SortedSet.intersection`
* :func:`SortedSet.intersection_update`
* :func:`SortedSet.symmetric_difference`
* :func:`SortedSet.symmetric_difference_update`
* :func:`SortedSet.union`
* :func:`SortedSet.update`
Methods for miscellany:
* :func:`SortedSet.copy`
* :func:`SortedSet.count`
* :func:`SortedSet.__repr__`
* :func:`SortedSet._check`
Sorted list methods available:
* :func:`SortedList.bisect_left`
* :func:`SortedList.bisect_right`
* :func:`SortedList.index`
* :func:`SortedList.irange`
* :func:`SortedList.islice`
* :func:`SortedList._reset`
Additional sorted list methods available, if key-function used:
* :func:`SortedKeyList.bisect_key_left`
* :func:`SortedKeyList.bisect_key_right`
* :func:`SortedKeyList.irange_key`
Sorted set comparisons use subset and superset relations. Two sorted sets
are equal if and only if every element of each sorted set is contained in
the other (each is a subset of the other). A sorted set is less than
another sorted set if and only if the first sorted set is a proper subset
of the second sorted set (is a subset, but is not equal). A sorted set is
greater than another sorted set if and only if the first sorted set is a
proper superset of the second sorted set (is a superset, but is not equal).
"""
def __init__(self, iterable=None, key=None):
"""Initialize sorted set instance.
Optional `iterable` argument provides an initial iterable of values to
initialize the sorted set.
Optional `key` argument defines a callable that, like the `key`
argument to Python's `sorted` function, extracts a comparison key from
each value. The default, none, compares values directly.
Runtime complexity: `O(n*log(n))`
>>> ss = SortedSet([3, 1, 2, 5, 4])
>>> ss
SortedSet([1, 2, 3, 4, 5])
>>> from operator import neg
>>> ss = SortedSet([3, 1, 2, 5, 4], neg)
>>> ss
SortedSet([5, 4, 3, 2, 1], key=<built-in function neg>)
:param iterable: initial values (optional)
:param key: function used to extract comparison key (optional)
"""
self._key = key
# SortedSet._fromset calls SortedSet.__init__ after initializing the
# _set attribute. So only create a new set if the _set attribute is not
# already present.
if not hasattr(self, '_set'):
self._set = set()
self._list = SortedList(self._set, key=key)
# Expose some set methods publicly.
_set = self._set
self.isdisjoint = _set.isdisjoint
self.issubset = _set.issubset
self.issuperset = _set.issuperset
# Expose some sorted list methods publicly.
_list = self._list
self.bisect_left = _list.bisect_left
self.bisect = _list.bisect
self.bisect_right = _list.bisect_right
self.index = _list.index
self.irange = _list.irange
self.islice = _list.islice
self._reset = _list._reset
if key is not None:
self.bisect_key_left = _list.bisect_key_left
self.bisect_key_right = _list.bisect_key_right
self.bisect_key = _list.bisect_key
self.irange_key = _list.irange_key
if iterable is not None:
self._update(iterable)
@classmethod
def _fromset(cls, values, key=None):
"""Initialize sorted set from existing set.
Used internally by set operations that return a new set.
"""
sorted_set = object.__new__(cls)
sorted_set._set = values
sorted_set.__init__(key=key)
return sorted_set
@property
def key(self):
"""Function used to extract comparison key from values.
Sorted set compares values directly when the key function is none.
"""
return self._key
def __contains__(self, value):
"""Return true if `value` is an element of the sorted set.
``ss.__contains__(value)`` <==> ``value in ss``
Runtime complexity: `O(1)`
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> 3 in ss
True
:param value: search for value in sorted set
:return: true if `value` in sorted set
"""
return value in self._set
def __getitem__(self, index):
"""Lookup value at `index` in sorted set.
``ss.__getitem__(index)`` <==> ``ss[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet('abcde')
>>> ss[2]
'c'
>>> ss[-1]
'e'
>>> ss[2:5]
['c', 'd', 'e']
:param index: integer or slice for indexing
:return: value or list of values
:raises IndexError: if index out of range
"""
return self._list[index]
def __delitem__(self, index):
"""Remove value at `index` from sorted set.
``ss.__delitem__(index)`` <==> ``del ss[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet('abcde')
>>> del ss[2]
>>> ss
SortedSet(['a', 'b', 'd', 'e'])
>>> del ss[:2]
>>> ss
SortedSet(['d', 'e'])
:param index: integer or slice for indexing
:raises IndexError: if index out of range
"""
_set = self._set
_list = self._list
if isinstance(index, slice):
values = _list[index]
_set.difference_update(values)
else:
value = _list[index]
_set.remove(value)
del _list[index]
def __make_cmp(set_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted set and set."
if isinstance(other, SortedSet):
return set_op(self._set, other._set)
elif isinstance(other, Set):
return set_op(self._set, other)
return NotImplemented
set_op_name = set_op.__name__
comparer.__name__ = '__{0}__'.format(set_op_name)
doc_str = """Return true if and only if sorted set is {0} `other`.
``ss.__{1}__(other)`` <==> ``ss {2} other``
Comparisons use subset and superset semantics as with sets.
Runtime complexity: `O(n)`
:param other: `other` set
:return: true if sorted set is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, set_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, '==', 'equal to')
__ne__ = __make_cmp(ne, '!=', 'not equal to')
__lt__ = __make_cmp(lt, '<', 'a proper subset of')
__gt__ = __make_cmp(gt, '>', 'a proper superset of')
__le__ = __make_cmp(le, '<=', 'a subset of')
__ge__ = __make_cmp(ge, '>=', 'a superset of')
__make_cmp = staticmethod(__make_cmp)
def __len__(self):
"""Return the size of the sorted set.
``ss.__len__()`` <==> ``len(ss)``
:return: size of sorted set
"""
return len(self._set)
def __iter__(self):
"""Return an iterator over the sorted set.
``ss.__iter__()`` <==> ``iter(ss)``
Iterating the sorted set while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return iter(self._list)
def __reversed__(self):
"""Return a reverse iterator over the sorted set.
``ss.__reversed__()`` <==> ``reversed(ss)``
Iterating the sorted set while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return reversed(self._list)
def add(self, value):
"""Add `value` to sorted set.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet()
>>> ss.add(3)
>>> ss.add(1)
>>> ss.add(2)
>>> ss
SortedSet([1, 2, 3])
:param value: value to add to sorted set
"""
_set = self._set
if value not in _set:
_set.add(value)
self._list.add(value)
_add = add
def clear(self):
"""Remove all values from sorted set.
Runtime complexity: `O(n)`
"""
self._set.clear()
self._list.clear()
def copy(self):
"""Return a shallow copy of the sorted set.
Runtime complexity: `O(n)`
:return: new sorted set
"""
return self._fromset(set(self._set), key=self._key)
__copy__ = copy
def count(self, value):
"""Return number of occurrences of `value` in the sorted set.
Runtime complexity: `O(1)`
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.count(3)
1
:param value: value to count in sorted set
:return: count
"""
return 1 if value in self._set else 0
def discard(self, value):
"""Remove `value` from sorted set if it is a member.
If `value` is not a member, do nothing.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.discard(5)
>>> ss.discard(0)
>>> ss == set([1, 2, 3, 4])
True
:param value: `value` to discard from sorted set
"""
_set = self._set
if value in _set:
_set.remove(value)
self._list.remove(value)
_discard = discard
def pop(self, index=-1):
"""Remove and return value at `index` in sorted set.
Raise :exc:`IndexError` if the sorted set is empty or index is out of
range.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet('abcde')
>>> ss.pop()
'e'
>>> ss.pop(2)
'c'
>>> ss
SortedSet(['a', 'b', 'd'])
:param int index: index of value (default -1)
:return: value
:raises IndexError: if index is out of range
"""
# pylint: disable=arguments-differ
value = self._list.pop(index)
self._set.remove(value)
return value
def remove(self, value):
"""Remove `value` from sorted set; `value` must be a member.
If `value` is not a member, raise :exc:`KeyError`.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.remove(5)
>>> ss == set([1, 2, 3, 4])
True
>>> ss.remove(0)
Traceback (most recent call last):
...
KeyError: 0
:param value: `value` to remove from sorted set
:raises KeyError: if `value` is not in sorted set
"""
self._set.remove(value)
self._list.remove(value)
def difference(self, *iterables):
"""Return the difference of two or more sets as a new sorted set.
The `difference` method also corresponds to operator ``-``.
``ss.__sub__(iterable)`` <==> ``ss - iterable``
The difference is all values that are in this sorted set but not the
other `iterables`.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.difference([4, 5, 6, 7])
SortedSet([1, 2, 3])
:param iterables: iterable arguments
:return: new sorted set
"""
diff = self._set.difference(*iterables)
return self._fromset(diff, key=self._key)
__sub__ = difference
def difference_update(self, *iterables):
"""Remove all values of `iterables` from this sorted set.
The `difference_update` method also corresponds to operator ``-=``.
``ss.__isub__(iterable)`` <==> ``ss -= iterable``
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> _ = ss.difference_update([4, 5, 6, 7])
>>> ss
SortedSet([1, 2, 3])
:param iterables: iterable arguments
:return: itself
"""
_set = self._set
_list = self._list
values = set(chain(*iterables))
if (4 * len(values)) > len(_set):
_set.difference_update(values)
_list.clear()
_list.update(_set)
else:
_discard = self._discard
for value in values:
_discard(value)
return self
__isub__ = difference_update
def intersection(self, *iterables):
"""Return the intersection of two or more sets as a new sorted set.
The `intersection` method also corresponds to operator ``&``.
``ss.__and__(iterable)`` <==> ``ss & iterable``
The intersection is all values that are in this sorted set and each of
the other `iterables`.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.intersection([4, 5, 6, 7])
SortedSet([4, 5])
:param iterables: iterable arguments
:return: new sorted set
"""
intersect = self._set.intersection(*iterables)
return self._fromset(intersect, key=self._key)
__and__ = intersection
__rand__ = __and__
def intersection_update(self, *iterables):
"""Update the sorted set with the intersection of `iterables`.
The `intersection_update` method also corresponds to operator ``&=``.
``ss.__iand__(iterable)`` <==> ``ss &= iterable``
Keep only values found in itself and all `iterables`.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> _ = ss.intersection_update([4, 5, 6, 7])
>>> ss
SortedSet([4, 5])
:param iterables: iterable arguments
:return: itself
"""
_set = self._set
_list = self._list
_set.intersection_update(*iterables)
_list.clear()
_list.update(_set)
return self
__iand__ = intersection_update
def symmetric_difference(self, other):
"""Return the symmetric difference with `other` as a new sorted set.
The `symmetric_difference` method also corresponds to operator ``^``.
``ss.__xor__(other)`` <==> ``ss ^ other``
The symmetric difference is all values tha are in exactly one of the
sets.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.symmetric_difference([4, 5, 6, 7])
SortedSet([1, 2, 3, 6, 7])
:param other: `other` iterable
:return: new sorted set
"""
diff = self._set.symmetric_difference(other)
return self._fromset(diff, key=self._key)
__xor__ = symmetric_difference
__rxor__ = __xor__
def symmetric_difference_update(self, other):
"""Update the sorted set with the symmetric difference with `other`.
The `symmetric_difference_update` method also corresponds to operator
``^=``.
``ss.__ixor__(other)`` <==> ``ss ^= other``
Keep only values found in exactly one of itself and `other`.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> _ = ss.symmetric_difference_update([4, 5, 6, 7])
>>> ss
SortedSet([1, 2, 3, 6, 7])
:param other: `other` iterable
:return: itself
"""
_set = self._set
_list = self._list
_set.symmetric_difference_update(other)
_list.clear()
_list.update(_set)
return self
__ixor__ = symmetric_difference_update
def union(self, *iterables):
"""Return new sorted set with values from itself and all `iterables`.
The `union` method also corresponds to operator ``|``.
``ss.__or__(iterable)`` <==> ``ss | iterable``
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.union([4, 5, 6, 7])
SortedSet([1, 2, 3, 4, 5, 6, 7])
:param iterables: iterable arguments
:return: new sorted set
"""
return self.__class__(chain(iter(self), *iterables), key=self._key)
__or__ = union
__ror__ = __or__
def update(self, *iterables):
"""Update the sorted set adding values from all `iterables`.
The `update` method also corresponds to operator ``|=``.
``ss.__ior__(iterable)`` <==> ``ss |= iterable``
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> _ = ss.update([4, 5, 6, 7])
>>> ss
SortedSet([1, 2, 3, 4, 5, 6, 7])
:param iterables: iterable arguments
:return: itself
"""
_set = self._set
_list = self._list
values = set(chain(*iterables))
if (4 * len(values)) > len(_set):
_list = self._list
_set.update(values)
_list.clear()
_list.update(_set)
else:
_add = self._add
for value in values:
_add(value)
return self
__ior__ = update
_update = update
def __reduce__(self):
"""Support for pickle.
The tricks played with exposing methods in :func:`SortedSet.__init__`
confuse pickle so customize the reducer.
"""
return (type(self), (self._set, self._key))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted set.
``ss.__repr__()`` <==> ``repr(ss)``
:return: string representation
"""
_key = self._key
key = '' if _key is None else ', key={0!r}'.format(_key)
type_name = type(self).__name__
return '{0}({1!r}{2})'.format(type_name, list(self), key)
def _check(self):
"""Check invariants of sorted set.
Runtime complexity: `O(n)`
"""
_set = self._set
_list = self._list
_list._check()
assert len(_set) == len(_list)
assert all(value in _set for value in _list)
class SortedDict(dict):
"""Sorted dict is a sorted mutable mapping.
Sorted dict keys are maintained in sorted order. The design of sorted dict
is simple: sorted dict inherits from dict to store items and maintains a
sorted list of keys.
Sorted dict keys must be hashable and comparable. The hash and total
ordering of keys must not change while they are stored in the sorted dict.
Mutable mapping methods:
* :func:`SortedDict.__getitem__` (inherited from dict)
* :func:`SortedDict.__setitem__`
* :func:`SortedDict.__delitem__`
* :func:`SortedDict.__iter__`
* :func:`SortedDict.__len__` (inherited from dict)
Methods for adding items:
* :func:`SortedDict.setdefault`
* :func:`SortedDict.update`
Methods for removing items:
* :func:`SortedDict.clear`
* :func:`SortedDict.pop`
* :func:`SortedDict.popitem`
Methods for looking up items:
* :func:`SortedDict.__contains__` (inherited from dict)
* :func:`SortedDict.get` (inherited from dict)
* :func:`SortedDict.peekitem`
Methods for views:
* :func:`SortedDict.keys`
* :func:`SortedDict.items`
* :func:`SortedDict.values`
Methods for miscellany:
* :func:`SortedDict.copy`
* :func:`SortedDict.fromkeys`
* :func:`SortedDict.__reversed__`
* :func:`SortedDict.__eq__` (inherited from dict)
* :func:`SortedDict.__ne__` (inherited from dict)
* :func:`SortedDict.__repr__`
* :func:`SortedDict._check`
Sorted list methods available (applies to keys):
* :func:`SortedList.bisect_left`
* :func:`SortedList.bisect_right`
* :func:`SortedList.count`
* :func:`SortedList.index`
* :func:`SortedList.irange`
* :func:`SortedList.islice`
* :func:`SortedList._reset`
Additional sorted list methods available, if key-function used:
* :func:`SortedKeyList.bisect_key_left`
* :func:`SortedKeyList.bisect_key_right`
* :func:`SortedKeyList.irange_key`
Sorted dicts may only be compared for equality and inequality.
"""
def __init__(self, *args, **kwargs):
"""Initialize sorted dict instance.
Optional key-function argument defines a callable that, like the `key`
argument to the built-in `sorted` function, extracts a comparison key
from each dictionary key. If no function is specified, the default
compares the dictionary keys directly. The key-function argument must
be provided as a positional argument and must come before all other
arguments.
Optional iterable argument provides an initial sequence of pairs to
initialize the sorted dict. Each pair in the sequence defines the key
and corresponding value. If a key is seen more than once, the last
value associated with it is stored in the new sorted dict.
Optional mapping argument provides an initial mapping of items to
initialize the sorted dict.
If keyword arguments are given, the keywords themselves, with their
associated values, are added as items to the dictionary. If a key is
specified both in the positional argument and as a keyword argument,
the value associated with the keyword is stored in the
sorted dict.
Sorted dict keys must be hashable, per the requirement for Python's
dictionaries. Keys (or the result of the key-function) must also be
comparable, per the requirement for sorted lists.
>>> d = {'alpha': 1, 'beta': 2}
>>> SortedDict([('alpha', 1), ('beta', 2)]) == d
True
>>> SortedDict({'alpha': 1, 'beta': 2}) == d
True
>>> SortedDict(alpha=1, beta=2) == d
True
"""
if args and (args[0] is None or callable(args[0])):
_key = self._key = args[0]
args = args[1:]
else:
_key = self._key = None
self._list = SortedList(key=_key)
# Reaching through ``self._list`` repeatedly adds unnecessary overhead
# so cache references to sorted list methods.
_list = self._list
self._list_add = _list.add
self._list_clear = _list.clear
self._list_iter = _list.__iter__
self._list_reversed = _list.__reversed__
self._list_pop = _list.pop
self._list_remove = _list.remove
self._list_update = _list.update
# Expose some sorted list methods publicly.
self.bisect_left = _list.bisect_left
self.bisect = _list.bisect_right
self.bisect_right = _list.bisect_right
self.index = _list.index
self.irange = _list.irange
self.islice = _list.islice
self._reset = _list._reset
if _key is not None:
self.bisect_key_left = _list.bisect_key_left
self.bisect_key_right = _list.bisect_key_right
self.bisect_key = _list.bisect_key
self.irange_key = _list.irange_key
self._update(*args, **kwargs)
@property
def key(self):
"""Function used to extract comparison key from keys.
Sorted dict compares keys directly when the key function is none.
"""
return self._key
@property
def iloc(self):
"""Cached reference of sorted keys view.
Deprecated in version 2 of Sorted Containers. Use
:func:`SortedDict.keys` instead.
"""
# pylint: disable=attribute-defined-outside-init
try:
return self._iloc
except AttributeError:
warnings.warn(
'sorted_dict.iloc is deprecated.'
' Use SortedDict.keys() instead.',
DeprecationWarning,
stacklevel=2,
)
_iloc = self._iloc = SortedKeysView(self)
return _iloc
def clear(self):
"""Remove all items from sorted dict.
Runtime complexity: `O(n)`
"""
dict.clear(self)
self._list_clear()
def __delitem__(self, key):
"""Remove item from sorted dict identified by `key`.
``sd.__delitem__(key)`` <==> ``del sd[key]``
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> del sd['b']
>>> sd
SortedDict({'a': 1, 'c': 3})
>>> del sd['z']
Traceback (most recent call last):
...
KeyError: 'z'
:param key: `key` for item lookup
:raises KeyError: if key not found
"""
dict.__delitem__(self, key)
self._list_remove(key)
def __iter__(self):
"""Return an iterator over the keys of the sorted dict.
``sd.__iter__()`` <==> ``iter(sd)``
Iterating the sorted dict while adding or deleting items may raise a
:exc:`RuntimeError` or fail to iterate over all keys.
"""
return self._list_iter()
def __reversed__(self):
"""Return a reverse iterator over the keys of the sorted dict.
``sd.__reversed__()`` <==> ``reversed(sd)``
Iterating the sorted dict while adding or deleting items may raise a
:exc:`RuntimeError` or fail to iterate over all keys.
"""
return self._list_reversed()
def __setitem__(self, key, value):
"""Store item in sorted dict with `key` and corresponding `value`.
``sd.__setitem__(key, value)`` <==> ``sd[key] = value``
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict()
>>> sd['c'] = 3
>>> sd['a'] = 1
>>> sd['b'] = 2
>>> sd
SortedDict({'a': 1, 'b': 2, 'c': 3})
:param key: key for item
:param value: value for item
"""
if key not in self:
self._list_add(key)
dict.__setitem__(self, key, value)
_setitem = __setitem__
def copy(self):
"""Return a shallow copy of the sorted dict.
Runtime complexity: `O(n)`
:return: new sorted dict
"""
return self.__class__(self._key, list(self.items()))
__copy__ = copy
@classmethod
def fromkeys(cls, iterable, value=None):
"""Return a new sorted dict initailized from `iterable` and `value`.
Items in the sorted dict have keys from `iterable` and values equal to
`value`.
Runtime complexity: `O(n*log(n))`
:return: new sorted dict
"""
return cls((key, value) for key in iterable)
def keys(self):
"""Return new sorted keys view of the sorted dict's keys.
See :class:`SortedKeysView` for details.
:return: new sorted keys view
"""
return SortedKeysView(self)
def items(self):
"""Return new sorted items view of the sorted dict's items.
See :class:`SortedItemsView` for details.
:return: new sorted items view
"""
return SortedItemsView(self)
def values(self):
"""Return new sorted values view of the sorted dict's values.
See :class:`SortedValuesView` for details.
:return: new sorted values view
"""
return SortedValuesView(self)
# if sys.hexversion < 0x03000000:
# def __make_raise_attributeerror(original, alternate):
# # pylint: disable=no-self-argument
# message = (
# 'SortedDict.{original}() is not implemented.'
# ' Use SortedDict.{alternate}() instead.'
# ).format(original=original, alternate=alternate)
# def method(self):
# # pylint: disable=missing-docstring,unused-argument
# raise AttributeError(message)
# method.__name__ = original # pylint: disable=non-str-assignment-to-dunder-name
# method.__doc__ = message
# return property(method)
# iteritems = __make_raise_attributeerror('iteritems', 'items')
# iterkeys = __make_raise_attributeerror('iterkeys', 'keys')
# itervalues = __make_raise_attributeerror('itervalues', 'values')
# viewitems = __make_raise_attributeerror('viewitems', 'items')
# viewkeys = __make_raise_attributeerror('viewkeys', 'keys')
# viewvalues = __make_raise_attributeerror('viewvalues', 'values')
class _NotGiven(object):
# pylint: disable=too-few-public-methods
def __repr__(self):
return '<not-given>'
__not_given = _NotGiven()
def pop(self, key, default=__not_given):
"""Remove and return value for item identified by `key`.
If the `key` is not found then return `default` if given. If `default`
is not given then raise :exc:`KeyError`.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> sd.pop('c')
3
>>> sd.pop('z', 26)
26
>>> sd.pop('y')
Traceback (most recent call last):
...
KeyError: 'y'
:param key: `key` for item
:param default: `default` value if key not found (optional)
:return: value for item
:raises KeyError: if `key` not found and `default` not given
"""
if key in self:
self._list_remove(key)
return dict.pop(self, key)
else:
if default is self.__not_given:
raise KeyError(key)
return default
def popitem(self, index=-1):
"""Remove and return ``(key, value)`` pair at `index` from sorted dict.
Optional argument `index` defaults to -1, the last item in the sorted
dict. Specify ``index=0`` for the first item in the sorted dict.
If the sorted dict is empty, raises :exc:`KeyError`.
If the `index` is out of range, raises :exc:`IndexError`.
Runtime complexity: `O(log(n))`
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> sd.popitem()
('c', 3)
>>> sd.popitem(0)
('a', 1)
>>> sd.popitem(100)
Traceback (most recent call last):
...
IndexError: list index out of range
:param int index: `index` of item (default -1)
:return: key and value pair
:raises KeyError: if sorted dict is empty
:raises IndexError: if `index` out of range
"""
if not self:
raise KeyError('popitem(): dictionary is empty')
key = self._list_pop(index)
value = dict.pop(self, key)
return (key, value)
def peekitem(self, index=-1):
"""Return ``(key, value)`` pair at `index` in sorted dict.
Optional argument `index` defaults to -1, the last item in the sorted
dict. Specify ``index=0`` for the first item in the sorted dict.
Unlike :func:`SortedDict.popitem`, the sorted dict is not modified.
If the `index` is out of range, raises :exc:`IndexError`.
Runtime complexity: `O(log(n))`
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> sd.peekitem()
('c', 3)
>>> sd.peekitem(0)
('a', 1)
>>> sd.peekitem(100)
Traceback (most recent call last):
...
IndexError: list index out of range
:param int index: index of item (default -1)
:return: key and value pair
:raises IndexError: if `index` out of range
"""
key = self._list[index]
return key, self[key]
def setdefault(self, key, default=None):
"""Return value for item identified by `key` in sorted dict.
If `key` is in the sorted dict then return its value. If `key` is not
in the sorted dict then insert `key` with value `default` and return
`default`.
Optional argument `default` defaults to none.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict()
>>> sd.setdefault('a', 1)
1
>>> sd.setdefault('a', 10)
1
>>> sd
SortedDict({'a': 1})
:param key: key for item
:param default: value for item (default None)
:return: value for item identified by `key`
"""
if key in self:
return self[key]
dict.__setitem__(self, key, default)
self._list_add(key)
return default
def update(self, *args, **kwargs):
"""Update sorted dict with items from `args` and `kwargs`.
Overwrites existing items.
Optional arguments `args` and `kwargs` may be a mapping, an iterable of
pairs or keyword arguments. See :func:`SortedDict.__init__` for
details.
:param args: mapping or iterable of pairs
:param kwargs: keyword arguments mapping
"""
if not self:
dict.update(self, *args, **kwargs)
self._list_update(dict.__iter__(self))
return
if not kwargs and len(args) == 1 and isinstance(args[0], dict):
pairs = args[0]
else:
pairs = dict(*args, **kwargs)
if (10 * len(pairs)) > len(self):
dict.update(self, pairs)
self._list_clear()
self._list_update(dict.__iter__(self))
else:
for key in pairs:
self._setitem(key, pairs[key])
_update = update
def __reduce__(self):
"""Support for pickle.
The tricks played with caching references in
:func:`SortedDict.__init__` confuse pickle so customize the reducer.
"""
items = dict.copy(self)
return (type(self), (self._key, items))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted dict.
``sd.__repr__()`` <==> ``repr(sd)``
:return: string representation
"""
_key = self._key
type_name = type(self).__name__
key_arg = '' if _key is None else '{0!r}, '.format(_key)
item_format = '{0!r}: {1!r}'.format
items = ', '.join(item_format(key, self[key]) for key in self._list)
return '{0}({1}{{{2}}})'.format(type_name, key_arg, items)
def _check(self):
"""Check invariants of sorted dict.
Runtime complexity: `O(n)`
"""
_list = self._list
_list._check()
assert len(self) == len(_list)
assert all(key in self for key in _list)
def _view_delitem(self, index):
"""Remove item at `index` from sorted dict.
``view.__delitem__(index)`` <==> ``del view[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> view = sd.keys()
>>> del view[0]
>>> sd
SortedDict({'b': 2, 'c': 3})
>>> del view[-1]
>>> sd
SortedDict({'b': 2})
>>> del view[:]
>>> sd
SortedDict({})
:param index: integer or slice for indexing
:raises IndexError: if index out of range
"""
_mapping = self._mapping
_list = _mapping._list
dict_delitem = dict.__delitem__
if isinstance(index, slice):
keys = _list[index]
del _list[index]
for key in keys:
dict_delitem(_mapping, key)
else:
key = _list.pop(index)
dict_delitem(_mapping, key)
class SortedKeysView(KeysView, Sequence):
"""Sorted keys view is a dynamic view of the sorted dict's keys.
When the sorted dict's keys change, the view reflects those changes.
The keys view implements the set and sequence abstract base classes.
"""
__slots__ = ()
@classmethod
def _from_iterable(cls, it):
return SortedSet(it)
def __getitem__(self, index):
"""Lookup key at `index` in sorted keys views.
``skv.__getitem__(index)`` <==> ``skv[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> skv = sd.keys()
>>> skv[0]
'a'
>>> skv[-1]
'c'
>>> skv[:]
['a', 'b', 'c']
>>> skv[100]
Traceback (most recent call last):
...
IndexError: list index out of range
:param index: integer or slice for indexing
:return: key or list of keys
:raises IndexError: if index out of range
"""
return self._mapping._list[index]
__delitem__ = _view_delitem
class SortedItemsView(ItemsView, Sequence):
"""Sorted items view is a dynamic view of the sorted dict's items.
When the sorted dict's items change, the view reflects those changes.
The items view implements the set and sequence abstract base classes.
"""
__slots__ = ()
@classmethod
def _from_iterable(cls, it):
return SortedSet(it)
def __getitem__(self, index):
"""Lookup item at `index` in sorted items view.
``siv.__getitem__(index)`` <==> ``siv[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> siv = sd.items()
>>> siv[0]
('a', 1)
>>> siv[-1]
('c', 3)
>>> siv[:]
[('a', 1), ('b', 2), ('c', 3)]
>>> siv[100]
Traceback (most recent call last):
...
IndexError: list index out of range
:param index: integer or slice for indexing
:return: item or list of items
:raises IndexError: if index out of range
"""
_mapping = self._mapping
_mapping_list = _mapping._list
if isinstance(index, slice):
keys = _mapping_list[index]
return [(key, _mapping[key]) for key in keys]
key = _mapping_list[index]
return key, _mapping[key]
__delitem__ = _view_delitem
class SortedValuesView(ValuesView, Sequence):
"""Sorted values view is a dynamic view of the sorted dict's values.
When the sorted dict's values change, the view reflects those changes.
The values view implements the sequence abstract base class.
"""
__slots__ = ()
def __getitem__(self, index):
"""Lookup value at `index` in sorted values view.
``siv.__getitem__(index)`` <==> ``siv[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> svv = sd.values()
>>> svv[0]
1
>>> svv[-1]
3
>>> svv[:]
[1, 2, 3]
>>> svv[100]
Traceback (most recent call last):
...
IndexError: list index out of range
:param index: integer or slice for indexing
:return: value or list of values
:raises IndexError: if index out of range
"""
_mapping = self._mapping
_mapping_list = _mapping._list
if isinstance(index, slice):
keys = _mapping_list[index]
return [_mapping[key] for key in keys]
key = _mapping_list[index]
return _mapping[key]
__delitem__ = _view_delitem
# Copyright 2014 - 2019 Grant Jenks
# https://github.com/grantjenks/python-sortedcontainers
from collections import deque
N,Q = list(map(int,input().split()))
d = [(10**10,-1,-1)]
SL = SortedList([])
for i in range(N):
S,T,X = list(map(int,input().split()))
d.append((S-X,1,X))
d.append((T-X,-1,X))
d.sort()
d = deque(d)
for i in range(Q):
D = int(eval(input()))
while D >= d[0][0]:
time,event,x = d.popleft()
if event == 1:
SL.add(x)
else:
SL.remove(x)
if SL:
print(SL[0])
else:
print(-1)
| """Sorted List
==============
:doc:`Sorted Containers<index>` is an Apache2 licensed Python sorted
collections library, written in pure-Python, and fast as C-extensions. The
:doc:`introduction<introduction>` is the best way to get started.
Sorted list implementations:
.. currentmodule:: sortedcontainers
* :class:`SortedList`
* :class:`SortedKeyList`
"""
# pylint: disable=too-many-lines
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
from collections.abc import Sequence, MutableSequence, ItemsView, KeysView, ValuesView, MutableSet, Set
from functools import wraps, reduce
from _thread import get_ident
def recursive_repr(fillvalue='...'):
"Decorator to make a repr function return fillvalue for a recursive call."
# pylint: disable=missing-docstring
# Copied from reprlib in Python 3
# https://hg.python.org/cpython/file/3.6/Lib/reprlib.py
def decorating_function(user_function):
repr_running = set()
@wraps(user_function)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper
return decorating_function
###############################################################################
# END Python 2/3 Shims
###############################################################################
class SortedList(MutableSequence):
"""Sorted list is a sorted mutable sequence.
Sorted list values are maintained in sorted order.
Sorted list values must be comparable. The total ordering of values must
not change while they are stored in the sorted list.
Methods for adding values:
* :func:`SortedList.add`
* :func:`SortedList.update`
* :func:`SortedList.__add__`
* :func:`SortedList.__iadd__`
* :func:`SortedList.__mul__`
* :func:`SortedList.__imul__`
Methods for removing values:
* :func:`SortedList.clear`
* :func:`SortedList.discard`
* :func:`SortedList.remove`
* :func:`SortedList.pop`
* :func:`SortedList.__delitem__`
Methods for looking up values:
* :func:`SortedList.bisect_left`
* :func:`SortedList.bisect_right`
* :func:`SortedList.count`
* :func:`SortedList.index`
* :func:`SortedList.__contains__`
* :func:`SortedList.__getitem__`
Methods for iterating values:
* :func:`SortedList.irange`
* :func:`SortedList.islice`
* :func:`SortedList.__iter__`
* :func:`SortedList.__reversed__`
Methods for miscellany:
* :func:`SortedList.copy`
* :func:`SortedList.__len__`
* :func:`SortedList.__repr__`
* :func:`SortedList._check`
* :func:`SortedList._reset`
Sorted lists use lexicographical ordering semantics when compared to other
sequences.
Some methods of mutable sequences are not supported and will raise
not-implemented error.
"""
DEFAULT_LOAD_FACTOR = 1000
def __init__(self, iterable=None, key=None):
"""Initialize sorted list instance.
Optional `iterable` argument provides an initial iterable of values to
initialize the sorted list.
Runtime complexity: `O(n*log(n))`
>>> sl = SortedList()
>>> sl
SortedList([])
>>> sl = SortedList([3, 1, 2, 5, 4])
>>> sl
SortedList([1, 2, 3, 4, 5])
:param iterable: initial values (optional)
"""
assert key is None
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
"""Create new sorted list or sorted-key list instance.
Optional `key`-function argument will return an instance of subtype
:class:`SortedKeyList`.
>>> sl = SortedList()
>>> isinstance(sl, SortedList)
True
>>> sl = SortedList(key=lambda x: -x)
>>> isinstance(sl, SortedList)
True
>>> isinstance(sl, SortedKeyList)
True
:param iterable: initial values (optional)
:param key: function used to extract comparison key (optional)
:return: sorted list or sorted-key list instance
"""
# pylint: disable=unused-argument
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedKeyList)
else:
raise TypeError('inherit SortedKeyList for key argument')
@property
def key(self): # pylint: disable=useless-return
"""Function used to extract comparison key from values.
Sorted list compares values directly so the key function is none.
"""
return None
def _reset(self, load):
"""Reset sorted list load factor.
The `load` specifies the load-factor of the list. The default load
factor of 1000 works well for lists from tens to tens-of-millions of
values. Good practice is to use a value that is the cube root of the
list size. With billions of elements, the best load factor depends on
your usage. It's best to leave the load factor at the default until you
start benchmarking.
See :doc:`implementation` and :doc:`performance-scale` for more
information.
Runtime complexity: `O(n)`
:param int load: load-factor for sorted list sublists
"""
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._update(values)
def clear(self):
"""Remove all values from sorted list.
Runtime complexity: `O(n)`
"""
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
self._offset = 0
_clear = clear
def add(self, value):
"""Add `value` to sorted list.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList()
>>> sl.add(3)
>>> sl.add(1)
>>> sl.add(2)
>>> sl
SortedList([1, 2, 3])
:param value: value to add to sorted list
"""
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
"""Split sublists with length greater than double the load-factor.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
"""
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
"""Update sorted list by adding all values from `iterable`.
Runtime complexity: `O(k*log(n))` -- approximate.
>>> sl = SortedList()
>>> sl.update([3, 1, 2])
>>> sl
SortedList([1, 2, 3])
:param iterable: iterable of values to add
"""
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list.
``sl.__contains__(value)`` <==> ``value in sl``
Runtime complexity: `O(log(n))`
>>> sl = SortedList([1, 2, 3, 4, 5])
>>> 3 in sl
True
:param value: search for value in sorted list
:return: true if `value` in sorted list
"""
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def discard(self, value):
"""Remove `value` from sorted list if it is a member.
If `value` is not a member, do nothing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([1, 2, 3, 4, 5])
>>> sl.discard(5)
>>> sl.discard(0)
>>> sl == [1, 2, 3, 4]
True
:param value: `value` to discard from sorted list
"""
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member.
If `value` is not a member, raise ValueError.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([1, 2, 3, 4, 5])
>>> sl.remove(5)
>>> sl == [1, 2, 3, 4]
True
>>> sl.remove(0)
Traceback (most recent call last):
...
ValueError: 0 not in list
:param value: `value` to remove from sorted list
:raises ValueError: if `value` is not in sorted list
"""
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
else:
raise ValueError('{0!r} not in list'.format(value))
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`.
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
:param int pos: lists index
:param int idx: sublist index
"""
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
"""Convert an index pair (lists index, sublist index) into a single
index number that corresponds to the position of the value in the
sorted list.
Many queries require the index be built. Details of the index are
described in ``SortedList._build_index``.
Indexing requires traversing the tree from a leaf node to the root. The
parent of each node is easily computable at ``(pos - 1) // 2``.
Left-child nodes are always at odd indices and right-child nodes are
always at even indices.
When traversing up from a right-child node, increment the total by the
left-child node.
The final index is the sum from traversal and the index in the sublist.
For example, using the index from ``SortedList._build_index``::
_index = 14 5 9 3 2 4 5
_offset = 3
Tree::
14
5 9
3 2 4 5
Converting an index pair (2, 3) into a single index involves iterating
like so:
1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify
the node as a left-child node. At such nodes, we simply traverse to
the parent.
2. At node 9, position 2, we recognize the node as a right-child node
and accumulate the left-child in our total. Total is now 5 and we
traverse to the parent at position 0.
3. Iteration ends at the root.
The index is then the sum of the total and sublist index: 5 + 3 = 8.
:param int pos: lists index
:param int idx: sublist index
:return: index in sorted list
"""
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
# Increment pos to point in the index to len(self._lists[pos]).
pos += self._offset
# Iterate until reaching the root of the index tree at pos = 0.
while pos:
# Right-child nodes are at odd indices. At such indices
# account the total below the left child node.
if not pos & 1:
total += _index[pos - 1]
# Advance pos to the parent node.
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
"""Convert an index into an index pair (lists index, sublist index)
that can be used to access the corresponding lists position.
Many queries require the index be built. Details of the index are
described in ``SortedList._build_index``.
Indexing requires traversing the tree to a leaf node. Each node has two
children which are easily computable. Given an index, pos, the
left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 +
2``.
When the index is less than the left-child, traversal moves to the
left sub-tree. Otherwise, the index is decremented by the left-child
and traversal moves to the right sub-tree.
At a child node, the indexing pair is computed from the relative
position of the child node as compared with the offset and the remaining
index.
For example, using the index from ``SortedList._build_index``::
_index = 14 5 9 3 2 4 5
_offset = 3
Tree::
14
5 9
3 2 4 5
Indexing position 8 involves iterating like so:
1. Starting at the root, position 0, 8 is compared with the left-child
node (5) which it is greater than. When greater the index is
decremented and the position is updated to the right child node.
2. At node 9 with index 3, we again compare the index to the left-child
node with value 4. Because the index is the less than the left-child
node, we simply traverse to the left.
3. At node 4 with index 3, we recognize that we are at a leaf node and
stop iterating.
4. To compute the sublist index, we subtract the offset from the index
of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we
simply use the index remaining from iteration. In this case, 3.
The final index pair from our example is (2, 3) which corresponds to
index 8 in the sorted list.
:param int idx: index in sorted list
:return: (lists index, sublist index) pair
"""
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError('list index out of range')
elif idx >= self._len:
raise IndexError('list index out of range')
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
"""Build a positional index for indexing the sorted list.
Indexes are represented as binary trees in a dense array notation
similar to a binary heap.
For example, given a lists representation storing integers::
0: [1, 2, 3]
1: [4, 5]
2: [6, 7, 8, 9]
3: [10, 11, 12, 13, 14]
The first transformation maps the sub-lists by their length. The
first row of the index is the length of the sub-lists::
0: [3, 2, 4, 5]
Each row after that is the sum of consecutive pairs of the previous
row::
1: [5, 9]
2: [14]
Finally, the index is built by concatenating these lists together::
_index = [14, 5, 9, 3, 2, 4, 5]
An offset storing the start of the first row is also stored::
_offset = 3
When built, the index can be used for efficient indexing into the list.
See the comment and notes on ``SortedList._pos`` for details.
"""
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, list(zip(head, tail))))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, list(zip(head, tail))))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
"""Remove value at `index` from sorted list.
``sl.__delitem__(index)`` <==> ``del sl[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> del sl[2]
>>> sl
SortedList(['a', 'b', 'd', 'e'])
>>> del sl[:2]
>>> sl
SortedList(['d', 'e'])
:param index: integer or slice for indexing
:raises IndexError: if index out of range
"""
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = list(range(start, stop, step))
# Delete items from greatest index to least so
# that the indices remain valid throughout iteration.
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
"""Lookup value at `index` in sorted list.
``sl.__getitem__(index)`` <==> ``sl[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> sl[1]
'b'
>>> sl[-1]
'e'
>>> sl[2:5]
['c', 'd', 'e']
:param index: integer or slice for indexing
:return: value or list of values
:raises IndexError: if index out of range
"""
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
# Whole slice optimization: start to stop slices the whole
# sorted list.
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
start_list = _lists[start_pos]
stop_idx = start_idx + stop - start
# Small slice optimization: start index and stop index are
# within the start list.
if len(start_list) >= stop_idx:
return start_list[start_idx:stop_idx]
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1):stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
# Return a list because a negative step could
# reverse the order of the items and this could
# be the desired behavior.
indices = list(range(start, stop, step))
return list(self._getitem(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError('list index out of range')
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
_getitem = __getitem__
def __setitem__(self, index, value):
"""Raise not-implemented error.
``sl.__setitem__(index, value)`` <==> ``sl[index] = value``
:raises NotImplementedError: use ``del sl[index]`` and
``sl.add(value)`` instead
"""
message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
raise NotImplementedError(message)
def __iter__(self):
"""Return an iterator over the sorted list.
``sl.__iter__()`` <==> ``iter(sl)``
Iterating the sorted list while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return chain.from_iterable(self._lists)
def __reversed__(self):
"""Return a reverse iterator over the sorted list.
``sl.__reversed__()`` <==> ``reversed(sl)``
Iterating the sorted list while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return chain.from_iterable(list(map(reversed, reversed(self._lists))))
def reverse(self):
"""Raise not-implemented error.
Sorted list maintains values in ascending sort order. Values may not be
reversed in-place.
Use ``reversed(sl)`` for an iterator over values in descending sort
order.
Implemented to override `MutableSequence.reverse` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``reversed(sl)`` instead
"""
raise NotImplementedError('use ``reversed(sl)`` instead')
def islice(self, start=None, stop=None, reverse=False):
"""Return an iterator that slices sorted list from `start` to `stop`.
The `start` and `stop` index are treated inclusive and exclusive,
respectively.
Both `start` and `stop` default to `None` which is automatically
inclusive of the beginning and end of the sorted list.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> sl = SortedList('abcdefghij')
>>> it = sl.islice(2, 6)
>>> list(it)
['c', 'd', 'e', 'f']
:param int start: start index (inclusive)
:param int stop: stop index (exclusive)
:param bool reverse: yield values in reverse order
:return: iterator
"""
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
"""Return an iterator that slices sorted list using two index pairs.
The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the
first inclusive and the latter exclusive. See `_pos` for details on how
an index is converted to an index pair.
When `reverse` is `True`, values are yielded from the iterator in
reverse order.
"""
_lists = self._lists
if min_pos > max_pos:
return iter(())
if min_pos == max_pos:
if reverse:
indices = reversed(list(range(min_idx, max_idx)))
return list(map(_lists[min_pos].__getitem__, indices))
indices = list(range(min_idx, max_idx))
return list(map(_lists[min_pos].__getitem__, indices))
next_pos = min_pos + 1
if next_pos == max_pos:
if reverse:
min_indices = list(range(min_idx, len(_lists[min_pos])))
max_indices = list(range(max_idx))
return chain(
list(map(_lists[max_pos].__getitem__, reversed(max_indices))),
list(map(_lists[min_pos].__getitem__, reversed(min_indices))),
)
min_indices = list(range(min_idx, len(_lists[min_pos])))
max_indices = list(range(max_idx))
return chain(
list(map(_lists[min_pos].__getitem__, min_indices)),
list(map(_lists[max_pos].__getitem__, max_indices)),
)
if reverse:
min_indices = list(range(min_idx, len(_lists[min_pos])))
sublist_indices = list(range(next_pos, max_pos))
sublists = list(map(_lists.__getitem__, reversed(sublist_indices)))
max_indices = list(range(max_idx))
return chain(
list(map(_lists[max_pos].__getitem__, reversed(max_indices))),
chain.from_iterable(list(map(reversed, sublists))),
list(map(_lists[min_pos].__getitem__, reversed(min_indices))),
)
min_indices = list(range(min_idx, len(_lists[min_pos])))
sublist_indices = list(range(next_pos, max_pos))
sublists = list(map(_lists.__getitem__, sublist_indices))
max_indices = list(range(max_idx))
return chain(
list(map(_lists[min_pos].__getitem__, min_indices)),
chain.from_iterable(sublists),
list(map(_lists[max_pos].__getitem__, max_indices)),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
"""Create an iterator of values between `minimum` and `maximum`.
Both `minimum` and `maximum` default to `None` which is automatically
inclusive of the beginning and end of the sorted list.
The argument `inclusive` is a pair of booleans that indicates whether
the minimum and maximum ought to be included in the range,
respectively. The default is ``(True, True)`` such that the range is
inclusive of both minimum and maximum.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> sl = SortedList('abcdefghij')
>>> it = sl.irange('c', 'f')
>>> list(it)
['c', 'd', 'e', 'f']
:param minimum: minimum value to start iterating
:param maximum: maximum value to stop iterating
:param inclusive: pair of booleans
:param bool reverse: yield values in reverse order
:return: iterator
"""
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
"""Return the size of the sorted list.
``sl.__len__()`` <==> ``len(sl)``
:return: size of sorted list
"""
return self._len
def bisect_left(self, value):
"""Return an index to insert `value` in the sorted list.
If the `value` is already present, the insertion point will be before
(to the left of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([10, 11, 12, 13, 14])
>>> sl.bisect_left(12)
2
:param value: insertion index of value in sorted list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], value)
return self._loc(pos, idx)
def bisect_right(self, value):
"""Return an index to insert `value` in the sorted list.
Similar to `bisect_left`, but if `value` is already present, the
insertion point will be after (to the right of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([10, 11, 12, 13, 14])
>>> sl.bisect_right(12)
3
:param value: insertion index of value in sorted list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], value)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, value):
"""Return number of occurrences of `value` in the sorted list.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
>>> sl.count(3)
3
:param value: value to count in sorted list
:return: count
"""
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
"""Return a shallow copy of the sorted list.
Runtime complexity: `O(n)`
:return: new sorted list
"""
return self.__class__(self)
__copy__ = copy
def append(self, value):
"""Raise not-implemented error.
Implemented to override `MutableSequence.append` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``sl.add(value)`` instead
"""
raise NotImplementedError('use ``sl.add(value)`` instead')
def extend(self, values):
"""Raise not-implemented error.
Implemented to override `MutableSequence.extend` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``sl.update(values)`` instead
"""
raise NotImplementedError('use ``sl.update(values)`` instead')
def insert(self, index, value):
"""Raise not-implemented error.
:raises NotImplementedError: use ``sl.add(value)`` instead
"""
raise NotImplementedError('use ``sl.add(value)`` instead')
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list.
Raise :exc:`IndexError` if the sorted list is empty or index is out of
range.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> sl.pop()
'e'
>>> sl.pop(2)
'c'
>>> sl
SortedList(['a', 'b', 'd'])
:param int index: index of value (default -1)
:return: value
:raises IndexError: if index is out of range
"""
if not self._len:
raise IndexError('pop index out of range')
_lists = self._lists
if index == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if index == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=None, stop=None):
"""Return first index of value in sorted list.
Raise ValueError if `value` is not present.
Index must be between `start` and `stop` for the `value` to be
considered present. The default value, None, for `start` and `stop`
indicate the beginning and end of the sorted list.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> sl.index('d')
3
>>> sl.index('z')
Traceback (most recent call last):
...
ValueError: 'z' is not in list
:param value: value in sorted list
:param int start: start index (default None, start of sorted list)
:param int stop: stop index (default None, end of sorted list)
:return: index of value
:raises ValueError: if value is not present
"""
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(value) - 1
if start <= right:
return start
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
"""Return new sorted list containing all values in both sequences.
``sl.__add__(other)`` <==> ``sl + other``
Values in `other` do not need to be in sorted order.
Runtime complexity: `O(n*log(n))`
>>> sl1 = SortedList('bat')
>>> sl2 = SortedList('cat')
>>> sl1 + sl2
SortedList(['a', 'a', 'b', 'c', 't', 't'])
:param other: other iterable
:return: new sorted list
"""
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
"""Update sorted list with values from `other`.
``sl.__iadd__(other)`` <==> ``sl += other``
Values in `other` do not need to be in sorted order.
Runtime complexity: `O(k*log(n))` -- approximate.
>>> sl = SortedList('bat')
>>> sl += 'cat'
>>> sl
SortedList(['a', 'a', 'b', 'c', 't', 't'])
:param other: other iterable
:return: existing sorted list
"""
self._update(other)
return self
def __mul__(self, num):
"""Return new sorted list with `num` shallow copies of values.
``sl.__mul__(num)`` <==> ``sl * num``
Runtime complexity: `O(n*log(n))`
>>> sl = SortedList('abc')
>>> sl * 3
SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])
:param int num: count of shallow copies
:return: new sorted list
"""
values = reduce(iadd, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
"""Update the sorted list with `num` shallow copies of values.
``sl.__imul__(num)`` <==> ``sl *= num``
Runtime complexity: `O(n*log(n))`
>>> sl = SortedList('abc')
>>> sl *= 3
>>> sl
SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])
:param int num: count of shallow copies
:return: existing sorted list
"""
values = reduce(iadd, self._lists, []) * num
self._clear()
self._update(values)
return self
def __make_cmp(seq_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted list and sequence."
if not isinstance(other, Sequence):
return NotImplemented
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is eq:
return False
if seq_op is ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
seq_op_name = seq_op.__name__
comparer.__name__ = '__{0}__'.format(seq_op_name)
doc_str = """Return true if and only if sorted list is {0} `other`.
``sl.__{1}__(other)`` <==> ``sl {2} other``
Comparisons use lexicographical order as with sequences.
Runtime complexity: `O(n)`
:param other: `other` sequence
:return: true if sorted list is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, '==', 'equal to')
__ne__ = __make_cmp(ne, '!=', 'not equal to')
__lt__ = __make_cmp(lt, '<', 'less than')
__gt__ = __make_cmp(gt, '>', 'greater than')
__le__ = __make_cmp(le, '<=', 'less than or equal to')
__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
__make_cmp = staticmethod(__make_cmp)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values,))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted list.
``sl.__repr__()`` <==> ``repr(sl)``
:return: string representation
"""
return '{0}({1!r})'.format(type(self).__name__, list(self))
def _check(self):
"""Check invariants of sorted list.
Runtime complexity: `O(n)`
"""
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists)
assert self._len == sum(len(sublist) for sublist in self._lists)
# Check all sublists are sorted.
for sublist in self._lists:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
# Check beginning/end of sublists are sorted.
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
# Check _maxes index is the last value of each sublist.
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._lists[pos][-1]
# Check sublist lengths are less than double load-factor.
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
# Check sublist lengths are greater than half load-factor for all
# but the last sublist.
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
# Check index leaf nodes equal length of sublists.
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
# Check index branch nodes are the sum of their children.
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except BaseException:
traceback.print_exc(file=sys.stdout)
print('len', self._len)
print('load', self._load)
print('offset', self._offset)
print('len_index', len(self._index))
print('index', self._index)
print('len_maxes', len(self._maxes))
print('maxes', self._maxes)
print('len_lists', len(self._lists))
print('lists', self._lists)
raise
def identity(value):
"Identity function."
return value
class SortedKeyList(SortedList):
"""Sorted-key list is a subtype of sorted list.
The sorted-key list maintains values in comparison order based on the
result of a key function applied to every value.
All the same methods that are available in :class:`SortedList` are also
available in :class:`SortedKeyList`.
Additional methods provided:
* :attr:`SortedKeyList.key`
* :func:`SortedKeyList.bisect_key_left`
* :func:`SortedKeyList.bisect_key_right`
* :func:`SortedKeyList.irange_key`
Some examples below use:
>>> from operator import neg
>>> neg
<built-in function neg>
>>> neg(1)
-1
"""
def __init__(self, iterable=None, key=identity):
"""Initialize sorted-key list instance.
Optional `iterable` argument provides an initial iterable of values to
initialize the sorted-key list.
Optional `key` argument defines a callable that, like the `key`
argument to Python's `sorted` function, extracts a comparison key from
each value. The default is the identity function.
Runtime complexity: `O(n*log(n))`
>>> from operator import neg
>>> skl = SortedKeyList(key=neg)
>>> skl
SortedKeyList([], key=<built-in function neg>)
>>> skl = SortedKeyList([3, 1, 2], key=neg)
>>> skl
SortedKeyList([3, 2, 1], key=<built-in function neg>)
:param iterable: initial values (optional)
:param key: function used to extract comparison key (optional)
"""
self._key = key
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._keys = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=identity):
return object.__new__(cls)
@property
def key(self):
"Function used to extract comparison key from values."
return self._key
def clear(self):
"""Remove all values from sorted-key list.
Runtime complexity: `O(n)`
"""
self._len = 0
del self._lists[:]
del self._keys[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, value):
"""Add `value` to sorted-key list.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList(key=neg)
>>> skl.add(3)
>>> skl.add(1)
>>> skl.add(2)
>>> skl
SortedKeyList([3, 2, 1], key=<built-in function neg>)
:param value: value to add to sorted-key list
"""
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(value)
if _maxes:
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_keys[pos].append(key)
_maxes[pos] = key
else:
idx = bisect_right(_keys[pos], key)
_lists[pos].insert(idx, value)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
_lists.append([value])
_keys.append([key])
_maxes.append(key)
self._len += 1
def _expand(self, pos):
"""Split sublists with length greater than double the load-factor.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
"""
_lists = self._lists
_keys = self._keys
_index = self._index
if len(_keys[pos]) > (self._load << 1):
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
_keys_pos = _keys[pos]
half = _lists_pos[_load:]
half_keys = _keys_pos[_load:]
del _lists_pos[_load:]
del _keys_pos[_load:]
_maxes[pos] = _keys_pos[-1]
_lists.insert(pos + 1, half)
_keys.insert(pos + 1, half_keys)
_maxes.insert(pos + 1, half_keys[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
"""Update sorted-key list by adding all values from `iterable`.
Runtime complexity: `O(k*log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList(key=neg)
>>> skl.update([3, 1, 2])
>>> skl
SortedKeyList([3, 2, 1], key=<built-in function neg>)
:param iterable: iterable of values to add
"""
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort(key=self._key)
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_keys.extend(list(map(self._key, _list)) for _list in _lists)
_maxes.extend(sublist[-1] for sublist in _keys)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
"""Return true if `value` is an element of the sorted-key list.
``skl.__contains__(value)`` <==> ``value in skl``
Runtime complexity: `O(log(n))`
>>> from operator import neg
>>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)
>>> 3 in skl
True
:param value: search for value in sorted-key list
:return: true if `value` in sorted-key list
"""
_maxes = self._maxes
if not _maxes:
return False
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return False
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return False
if _lists[pos][idx] == value:
return True
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return False
len_sublist = len(_keys[pos])
idx = 0
def discard(self, value):
"""Remove `value` from sorted-key list if it is a member.
If `value` is not a member, do nothing.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.discard(1)
>>> skl.discard(0)
>>> skl == [5, 4, 3, 2]
True
:param value: `value` to discard from sorted-key list
"""
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
def remove(self, value):
"""Remove `value` from sorted-key list; `value` must be a member.
If `value` is not a member, raise ValueError.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)
>>> skl.remove(5)
>>> skl == [4, 3, 2, 1]
True
>>> skl.remove(0)
Traceback (most recent call last):
...
ValueError: 0 not in list
:param value: `value` to remove from sorted-key list
:raises ValueError: if `value` is not in sorted-key list
"""
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} not in list'.format(value))
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`.
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
:param int pos: lists index
:param int idx: sublist index
"""
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_index = self._index
keys_pos = _keys[pos]
lists_pos = _lists[pos]
del keys_pos[idx]
del lists_pos[idx]
self._len -= 1
len_keys_pos = len(keys_pos)
if len_keys_pos > (self._load >> 1):
_maxes[pos] = keys_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_keys) > 1:
if not pos:
pos += 1
prev = pos - 1
_keys[prev].extend(_keys[pos])
_lists[prev].extend(_lists[pos])
_maxes[prev] = _keys[prev][-1]
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_keys_pos:
_maxes[pos] = keys_pos[-1]
else:
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
"""Create an iterator of values between `minimum` and `maximum`.
Both `minimum` and `maximum` default to `None` which is automatically
inclusive of the beginning and end of the sorted-key list.
The argument `inclusive` is a pair of booleans that indicates whether
the minimum and maximum ought to be included in the range,
respectively. The default is ``(True, True)`` such that the range is
inclusive of both minimum and maximum.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> from operator import neg
>>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)
>>> it = skl.irange(14.5, 11.5)
>>> list(it)
[14, 13, 12]
:param minimum: minimum value to start iterating
:param maximum: maximum value to stop iterating
:param inclusive: pair of booleans
:param bool reverse: yield values in reverse order
:return: iterator
"""
min_key = self._key(minimum) if minimum is not None else None
max_key = self._key(maximum) if maximum is not None else None
return self._irange_key(
min_key=min_key, max_key=max_key,
inclusive=inclusive, reverse=reverse,
)
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),
reverse=False):
"""Create an iterator of values between `min_key` and `max_key`.
Both `min_key` and `max_key` default to `None` which is automatically
inclusive of the beginning and end of the sorted-key list.
The argument `inclusive` is a pair of booleans that indicates whether
the minimum and maximum ought to be included in the range,
respectively. The default is ``(True, True)`` such that the range is
inclusive of both minimum and maximum.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> from operator import neg
>>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)
>>> it = skl.irange_key(-14, -12)
>>> list(it)
[14, 13, 12]
:param min_key: minimum key to start iterating
:param max_key: maximum key to stop iterating
:param inclusive: pair of booleans
:param bool reverse: yield values in reverse order
:return: iterator
"""
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
_irange_key = irange_key
def bisect_left(self, value):
"""Return an index to insert `value` in the sorted-key list.
If the `value` is already present, the insertion point will be before
(to the left of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.bisect_left(1)
4
:param value: insertion index of value in sorted-key list
:return: index
"""
return self._bisect_key_left(self._key(value))
def bisect_right(self, value):
"""Return an index to insert `value` in the sorted-key list.
Similar to `bisect_left`, but if `value` is already present, the
insertion point will be after (to the right of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
>>> skl.bisect_right(1)
5
:param value: insertion index of value in sorted-key list
:return: index
"""
return self._bisect_key_right(self._key(value))
bisect = bisect_right
def bisect_key_left(self, key):
"""Return an index to insert `key` in the sorted-key list.
If the `key` is already present, the insertion point will be before (to
the left of) any existing keys.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.bisect_key_left(-1)
4
:param key: insertion index of key in sorted-key list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._keys[pos], key)
return self._loc(pos, idx)
_bisect_key_left = bisect_key_left
def bisect_key_right(self, key):
"""Return an index to insert `key` in the sorted-key list.
Similar to `bisect_key_left`, but if `key` is already present, the
insertion point will be after (to the right of) any existing keys.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
>>> skl.bisect_key_right(-1)
5
:param key: insertion index of key in sorted-key list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._keys[pos], key)
return self._loc(pos, idx)
bisect_key = bisect_key_right
_bisect_key_right = bisect_key_right
def count(self, value):
"""Return number of occurrences of `value` in the sorted-key list.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([4, 4, 4, 4, 3, 3, 3, 2, 2, 1], key=neg)
>>> skl.count(2)
2
:param value: value to count in sorted-key list
:return: count
"""
_maxes = self._maxes
if not _maxes:
return 0
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return 0
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
total = 0
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return total
if _lists[pos][idx] == value:
total += 1
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return total
len_sublist = len(_keys[pos])
idx = 0
def copy(self):
"""Return a shallow copy of the sorted-key list.
Runtime complexity: `O(n)`
:return: new sorted-key list
"""
return self.__class__(self, key=self._key)
__copy__ = copy
def index(self, value, start=None, stop=None):
"""Return first index of value in sorted-key list.
Raise ValueError if `value` is not present.
Index must be between `start` and `stop` for the `value` to be
considered present. The default value, None, for `start` and `stop`
indicate the beginning and end of the sorted-key list.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.index(2)
3
>>> skl.index(0)
Traceback (most recent call last):
...
ValueError: 0 is not in list
:param value: value in sorted-key list
:param int start: start index (default None, start of sorted-key list)
:param int stop: stop index (default None, end of sorted-key list)
:return: index of value
:raises ValueError: if value is not present
"""
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} is not in list'.format(value))
if _lists[pos][idx] == value:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} is not in list'.format(value))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
"""Return new sorted-key list containing all values in both sequences.
``skl.__add__(other)`` <==> ``skl + other``
Values in `other` do not need to be in sorted-key order.
Runtime complexity: `O(n*log(n))`
>>> from operator import neg
>>> skl1 = SortedKeyList([5, 4, 3], key=neg)
>>> skl2 = SortedKeyList([2, 1, 0], key=neg)
>>> skl1 + skl2
SortedKeyList([5, 4, 3, 2, 1, 0], key=<built-in function neg>)
:param other: other iterable
:return: new sorted-key list
"""
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values, key=self._key)
__radd__ = __add__
def __mul__(self, num):
"""Return new sorted-key list with `num` shallow copies of values.
``skl.__mul__(num)`` <==> ``skl * num``
Runtime complexity: `O(n*log(n))`
>>> from operator import neg
>>> skl = SortedKeyList([3, 2, 1], key=neg)
>>> skl * 2
SortedKeyList([3, 3, 2, 2, 1, 1], key=<built-in function neg>)
:param int num: count of shallow copies
:return: new sorted-key list
"""
values = reduce(iadd, self._lists, []) * num
return self.__class__(values, key=self._key)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values, self.key))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted-key list.
``skl.__repr__()`` <==> ``repr(skl)``
:return: string representation
"""
type_name = type(self).__name__
return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key)
def _check(self):
"""Check invariants of sorted-key list.
Runtime complexity: `O(n)`
"""
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists) == len(self._keys)
assert self._len == sum(len(sublist) for sublist in self._lists)
# Check all sublists are sorted.
for sublist in self._keys:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
# Check beginning/end of sublists are sorted.
for pos in range(1, len(self._keys)):
assert self._keys[pos - 1][-1] <= self._keys[pos][0]
# Check _keys matches _key mapped to _lists.
for val_sublist, key_sublist in zip(self._lists, self._keys):
assert len(val_sublist) == len(key_sublist)
for val, key in zip(val_sublist, key_sublist):
assert self._key(val) == key
# Check _maxes index is the last value of each sublist.
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._keys[pos][-1]
# Check sublist lengths are less than double load-factor.
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
# Check sublist lengths are greater than half load-factor for all
# but the last sublist.
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
# Check index leaf nodes equal length of sublists.
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
# Check index branch nodes are the sum of their children.
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except BaseException:
traceback.print_exc(file=sys.stdout)
print('len', self._len)
print('load', self._load)
print('offset', self._offset)
print('len_index', len(self._index))
print('index', self._index)
print('len_maxes', len(self._maxes))
print('maxes', self._maxes)
print('len_keys', len(self._keys))
print('keys', self._keys)
print('len_lists', len(self._lists))
print('lists', self._lists)
raise
class SortedSet(MutableSet, Sequence):
"""Sorted set is a sorted mutable set.
Sorted set values are maintained in sorted order. The design of sorted set
is simple: sorted set uses a set for set-operations and maintains a sorted
list of values.
Sorted set values must be hashable and comparable. The hash and total
ordering of values must not change while they are stored in the sorted set.
Mutable set methods:
* :func:`SortedSet.__contains__`
* :func:`SortedSet.__iter__`
* :func:`SortedSet.__len__`
* :func:`SortedSet.add`
* :func:`SortedSet.discard`
Sequence methods:
* :func:`SortedSet.__getitem__`
* :func:`SortedSet.__delitem__`
* :func:`SortedSet.__reversed__`
Methods for removing values:
* :func:`SortedSet.clear`
* :func:`SortedSet.pop`
* :func:`SortedSet.remove`
Set-operation methods:
* :func:`SortedSet.difference`
* :func:`SortedSet.difference_update`
* :func:`SortedSet.intersection`
* :func:`SortedSet.intersection_update`
* :func:`SortedSet.symmetric_difference`
* :func:`SortedSet.symmetric_difference_update`
* :func:`SortedSet.union`
* :func:`SortedSet.update`
Methods for miscellany:
* :func:`SortedSet.copy`
* :func:`SortedSet.count`
* :func:`SortedSet.__repr__`
* :func:`SortedSet._check`
Sorted list methods available:
* :func:`SortedList.bisect_left`
* :func:`SortedList.bisect_right`
* :func:`SortedList.index`
* :func:`SortedList.irange`
* :func:`SortedList.islice`
* :func:`SortedList._reset`
Additional sorted list methods available, if key-function used:
* :func:`SortedKeyList.bisect_key_left`
* :func:`SortedKeyList.bisect_key_right`
* :func:`SortedKeyList.irange_key`
Sorted set comparisons use subset and superset relations. Two sorted sets
are equal if and only if every element of each sorted set is contained in
the other (each is a subset of the other). A sorted set is less than
another sorted set if and only if the first sorted set is a proper subset
of the second sorted set (is a subset, but is not equal). A sorted set is
greater than another sorted set if and only if the first sorted set is a
proper superset of the second sorted set (is a superset, but is not equal).
"""
def __init__(self, iterable=None, key=None):
"""Initialize sorted set instance.
Optional `iterable` argument provides an initial iterable of values to
initialize the sorted set.
Optional `key` argument defines a callable that, like the `key`
argument to Python's `sorted` function, extracts a comparison key from
each value. The default, none, compares values directly.
Runtime complexity: `O(n*log(n))`
>>> ss = SortedSet([3, 1, 2, 5, 4])
>>> ss
SortedSet([1, 2, 3, 4, 5])
>>> from operator import neg
>>> ss = SortedSet([3, 1, 2, 5, 4], neg)
>>> ss
SortedSet([5, 4, 3, 2, 1], key=<built-in function neg>)
:param iterable: initial values (optional)
:param key: function used to extract comparison key (optional)
"""
self._key = key
# SortedSet._fromset calls SortedSet.__init__ after initializing the
# _set attribute. So only create a new set if the _set attribute is not
# already present.
if not hasattr(self, '_set'):
self._set = set()
self._list = SortedList(self._set, key=key)
# Expose some set methods publicly.
_set = self._set
self.isdisjoint = _set.isdisjoint
self.issubset = _set.issubset
self.issuperset = _set.issuperset
# Expose some sorted list methods publicly.
_list = self._list
self.bisect_left = _list.bisect_left
self.bisect = _list.bisect
self.bisect_right = _list.bisect_right
self.index = _list.index
self.irange = _list.irange
self.islice = _list.islice
self._reset = _list._reset
if key is not None:
self.bisect_key_left = _list.bisect_key_left
self.bisect_key_right = _list.bisect_key_right
self.bisect_key = _list.bisect_key
self.irange_key = _list.irange_key
if iterable is not None:
self._update(iterable)
@classmethod
def _fromset(cls, values, key=None):
"""Initialize sorted set from existing set.
Used internally by set operations that return a new set.
"""
sorted_set = object.__new__(cls)
sorted_set._set = values
sorted_set.__init__(key=key)
return sorted_set
@property
def key(self):
"""Function used to extract comparison key from values.
Sorted set compares values directly when the key function is none.
"""
return self._key
def __contains__(self, value):
"""Return true if `value` is an element of the sorted set.
``ss.__contains__(value)`` <==> ``value in ss``
Runtime complexity: `O(1)`
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> 3 in ss
True
:param value: search for value in sorted set
:return: true if `value` in sorted set
"""
return value in self._set
def __getitem__(self, index):
"""Lookup value at `index` in sorted set.
``ss.__getitem__(index)`` <==> ``ss[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet('abcde')
>>> ss[2]
'c'
>>> ss[-1]
'e'
>>> ss[2:5]
['c', 'd', 'e']
:param index: integer or slice for indexing
:return: value or list of values
:raises IndexError: if index out of range
"""
return self._list[index]
def __delitem__(self, index):
"""Remove value at `index` from sorted set.
``ss.__delitem__(index)`` <==> ``del ss[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet('abcde')
>>> del ss[2]
>>> ss
SortedSet(['a', 'b', 'd', 'e'])
>>> del ss[:2]
>>> ss
SortedSet(['d', 'e'])
:param index: integer or slice for indexing
:raises IndexError: if index out of range
"""
_set = self._set
_list = self._list
if isinstance(index, slice):
values = _list[index]
_set.difference_update(values)
else:
value = _list[index]
_set.remove(value)
del _list[index]
def __make_cmp(set_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted set and set."
if isinstance(other, SortedSet):
return set_op(self._set, other._set)
elif isinstance(other, Set):
return set_op(self._set, other)
return NotImplemented
set_op_name = set_op.__name__
comparer.__name__ = '__{0}__'.format(set_op_name)
doc_str = """Return true if and only if sorted set is {0} `other`.
``ss.__{1}__(other)`` <==> ``ss {2} other``
Comparisons use subset and superset semantics as with sets.
Runtime complexity: `O(n)`
:param other: `other` set
:return: true if sorted set is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, set_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, '==', 'equal to')
__ne__ = __make_cmp(ne, '!=', 'not equal to')
__lt__ = __make_cmp(lt, '<', 'a proper subset of')
__gt__ = __make_cmp(gt, '>', 'a proper superset of')
__le__ = __make_cmp(le, '<=', 'a subset of')
__ge__ = __make_cmp(ge, '>=', 'a superset of')
__make_cmp = staticmethod(__make_cmp)
def __len__(self):
"""Return the size of the sorted set.
``ss.__len__()`` <==> ``len(ss)``
:return: size of sorted set
"""
return len(self._set)
def __iter__(self):
"""Return an iterator over the sorted set.
``ss.__iter__()`` <==> ``iter(ss)``
Iterating the sorted set while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return iter(self._list)
def __reversed__(self):
"""Return a reverse iterator over the sorted set.
``ss.__reversed__()`` <==> ``reversed(ss)``
Iterating the sorted set while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return reversed(self._list)
def add(self, value):
"""Add `value` to sorted set.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet()
>>> ss.add(3)
>>> ss.add(1)
>>> ss.add(2)
>>> ss
SortedSet([1, 2, 3])
:param value: value to add to sorted set
"""
_set = self._set
if value not in _set:
_set.add(value)
self._list.add(value)
_add = add
def clear(self):
"""Remove all values from sorted set.
Runtime complexity: `O(n)`
"""
self._set.clear()
self._list.clear()
def copy(self):
"""Return a shallow copy of the sorted set.
Runtime complexity: `O(n)`
:return: new sorted set
"""
return self._fromset(set(self._set), key=self._key)
__copy__ = copy
def count(self, value):
"""Return number of occurrences of `value` in the sorted set.
Runtime complexity: `O(1)`
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.count(3)
1
:param value: value to count in sorted set
:return: count
"""
return 1 if value in self._set else 0
def discard(self, value):
"""Remove `value` from sorted set if it is a member.
If `value` is not a member, do nothing.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.discard(5)
>>> ss.discard(0)
>>> ss == set([1, 2, 3, 4])
True
:param value: `value` to discard from sorted set
"""
_set = self._set
if value in _set:
_set.remove(value)
self._list.remove(value)
_discard = discard
def pop(self, index=-1):
"""Remove and return value at `index` in sorted set.
Raise :exc:`IndexError` if the sorted set is empty or index is out of
range.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet('abcde')
>>> ss.pop()
'e'
>>> ss.pop(2)
'c'
>>> ss
SortedSet(['a', 'b', 'd'])
:param int index: index of value (default -1)
:return: value
:raises IndexError: if index is out of range
"""
# pylint: disable=arguments-differ
value = self._list.pop(index)
self._set.remove(value)
return value
def remove(self, value):
"""Remove `value` from sorted set; `value` must be a member.
If `value` is not a member, raise :exc:`KeyError`.
Runtime complexity: `O(log(n))` -- approximate.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.remove(5)
>>> ss == set([1, 2, 3, 4])
True
>>> ss.remove(0)
Traceback (most recent call last):
...
KeyError: 0
:param value: `value` to remove from sorted set
:raises KeyError: if `value` is not in sorted set
"""
self._set.remove(value)
self._list.remove(value)
def difference(self, *iterables):
"""Return the difference of two or more sets as a new sorted set.
The `difference` method also corresponds to operator ``-``.
``ss.__sub__(iterable)`` <==> ``ss - iterable``
The difference is all values that are in this sorted set but not the
other `iterables`.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.difference([4, 5, 6, 7])
SortedSet([1, 2, 3])
:param iterables: iterable arguments
:return: new sorted set
"""
diff = self._set.difference(*iterables)
return self._fromset(diff, key=self._key)
__sub__ = difference
def difference_update(self, *iterables):
"""Remove all values of `iterables` from this sorted set.
The `difference_update` method also corresponds to operator ``-=``.
``ss.__isub__(iterable)`` <==> ``ss -= iterable``
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> _ = ss.difference_update([4, 5, 6, 7])
>>> ss
SortedSet([1, 2, 3])
:param iterables: iterable arguments
:return: itself
"""
_set = self._set
_list = self._list
values = set(chain(*iterables))
if (4 * len(values)) > len(_set):
_set.difference_update(values)
_list.clear()
_list.update(_set)
else:
_discard = self._discard
for value in values:
_discard(value)
return self
__isub__ = difference_update
def intersection(self, *iterables):
"""Return the intersection of two or more sets as a new sorted set.
The `intersection` method also corresponds to operator ``&``.
``ss.__and__(iterable)`` <==> ``ss & iterable``
The intersection is all values that are in this sorted set and each of
the other `iterables`.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.intersection([4, 5, 6, 7])
SortedSet([4, 5])
:param iterables: iterable arguments
:return: new sorted set
"""
intersect = self._set.intersection(*iterables)
return self._fromset(intersect, key=self._key)
__and__ = intersection
__rand__ = __and__
def intersection_update(self, *iterables):
"""Update the sorted set with the intersection of `iterables`.
The `intersection_update` method also corresponds to operator ``&=``.
``ss.__iand__(iterable)`` <==> ``ss &= iterable``
Keep only values found in itself and all `iterables`.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> _ = ss.intersection_update([4, 5, 6, 7])
>>> ss
SortedSet([4, 5])
:param iterables: iterable arguments
:return: itself
"""
_set = self._set
_list = self._list
_set.intersection_update(*iterables)
_list.clear()
_list.update(_set)
return self
__iand__ = intersection_update
def symmetric_difference(self, other):
"""Return the symmetric difference with `other` as a new sorted set.
The `symmetric_difference` method also corresponds to operator ``^``.
``ss.__xor__(other)`` <==> ``ss ^ other``
The symmetric difference is all values tha are in exactly one of the
sets.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.symmetric_difference([4, 5, 6, 7])
SortedSet([1, 2, 3, 6, 7])
:param other: `other` iterable
:return: new sorted set
"""
diff = self._set.symmetric_difference(other)
return self._fromset(diff, key=self._key)
__xor__ = symmetric_difference
__rxor__ = __xor__
def symmetric_difference_update(self, other):
"""Update the sorted set with the symmetric difference with `other`.
The `symmetric_difference_update` method also corresponds to operator
``^=``.
``ss.__ixor__(other)`` <==> ``ss ^= other``
Keep only values found in exactly one of itself and `other`.
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> _ = ss.symmetric_difference_update([4, 5, 6, 7])
>>> ss
SortedSet([1, 2, 3, 6, 7])
:param other: `other` iterable
:return: itself
"""
_set = self._set
_list = self._list
_set.symmetric_difference_update(other)
_list.clear()
_list.update(_set)
return self
__ixor__ = symmetric_difference_update
def union(self, *iterables):
"""Return new sorted set with values from itself and all `iterables`.
The `union` method also corresponds to operator ``|``.
``ss.__or__(iterable)`` <==> ``ss | iterable``
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> ss.union([4, 5, 6, 7])
SortedSet([1, 2, 3, 4, 5, 6, 7])
:param iterables: iterable arguments
:return: new sorted set
"""
return self.__class__(chain(iter(self), *iterables), key=self._key)
__or__ = union
__ror__ = __or__
def update(self, *iterables):
"""Update the sorted set adding values from all `iterables`.
The `update` method also corresponds to operator ``|=``.
``ss.__ior__(iterable)`` <==> ``ss |= iterable``
>>> ss = SortedSet([1, 2, 3, 4, 5])
>>> _ = ss.update([4, 5, 6, 7])
>>> ss
SortedSet([1, 2, 3, 4, 5, 6, 7])
:param iterables: iterable arguments
:return: itself
"""
_set = self._set
_list = self._list
values = set(chain(*iterables))
if (4 * len(values)) > len(_set):
_list = self._list
_set.update(values)
_list.clear()
_list.update(_set)
else:
_add = self._add
for value in values:
_add(value)
return self
__ior__ = update
_update = update
def __reduce__(self):
"""Support for pickle.
The tricks played with exposing methods in :func:`SortedSet.__init__`
confuse pickle so customize the reducer.
"""
return (type(self), (self._set, self._key))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted set.
``ss.__repr__()`` <==> ``repr(ss)``
:return: string representation
"""
_key = self._key
key = '' if _key is None else ', key={0!r}'.format(_key)
type_name = type(self).__name__
return '{0}({1!r}{2})'.format(type_name, list(self), key)
def _check(self):
"""Check invariants of sorted set.
Runtime complexity: `O(n)`
"""
_set = self._set
_list = self._list
_list._check()
assert len(_set) == len(_list)
assert all(value in _set for value in _list)
class SortedDict(dict):
"""Sorted dict is a sorted mutable mapping.
Sorted dict keys are maintained in sorted order. The design of sorted dict
is simple: sorted dict inherits from dict to store items and maintains a
sorted list of keys.
Sorted dict keys must be hashable and comparable. The hash and total
ordering of keys must not change while they are stored in the sorted dict.
Mutable mapping methods:
* :func:`SortedDict.__getitem__` (inherited from dict)
* :func:`SortedDict.__setitem__`
* :func:`SortedDict.__delitem__`
* :func:`SortedDict.__iter__`
* :func:`SortedDict.__len__` (inherited from dict)
Methods for adding items:
* :func:`SortedDict.setdefault`
* :func:`SortedDict.update`
Methods for removing items:
* :func:`SortedDict.clear`
* :func:`SortedDict.pop`
* :func:`SortedDict.popitem`
Methods for looking up items:
* :func:`SortedDict.__contains__` (inherited from dict)
* :func:`SortedDict.get` (inherited from dict)
* :func:`SortedDict.peekitem`
Methods for views:
* :func:`SortedDict.keys`
* :func:`SortedDict.items`
* :func:`SortedDict.values`
Methods for miscellany:
* :func:`SortedDict.copy`
* :func:`SortedDict.fromkeys`
* :func:`SortedDict.__reversed__`
* :func:`SortedDict.__eq__` (inherited from dict)
* :func:`SortedDict.__ne__` (inherited from dict)
* :func:`SortedDict.__repr__`
* :func:`SortedDict._check`
Sorted list methods available (applies to keys):
* :func:`SortedList.bisect_left`
* :func:`SortedList.bisect_right`
* :func:`SortedList.count`
* :func:`SortedList.index`
* :func:`SortedList.irange`
* :func:`SortedList.islice`
* :func:`SortedList._reset`
Additional sorted list methods available, if key-function used:
* :func:`SortedKeyList.bisect_key_left`
* :func:`SortedKeyList.bisect_key_right`
* :func:`SortedKeyList.irange_key`
Sorted dicts may only be compared for equality and inequality.
"""
def __init__(self, *args, **kwargs):
"""Initialize sorted dict instance.
Optional key-function argument defines a callable that, like the `key`
argument to the built-in `sorted` function, extracts a comparison key
from each dictionary key. If no function is specified, the default
compares the dictionary keys directly. The key-function argument must
be provided as a positional argument and must come before all other
arguments.
Optional iterable argument provides an initial sequence of pairs to
initialize the sorted dict. Each pair in the sequence defines the key
and corresponding value. If a key is seen more than once, the last
value associated with it is stored in the new sorted dict.
Optional mapping argument provides an initial mapping of items to
initialize the sorted dict.
If keyword arguments are given, the keywords themselves, with their
associated values, are added as items to the dictionary. If a key is
specified both in the positional argument and as a keyword argument,
the value associated with the keyword is stored in the
sorted dict.
Sorted dict keys must be hashable, per the requirement for Python's
dictionaries. Keys (or the result of the key-function) must also be
comparable, per the requirement for sorted lists.
>>> d = {'alpha': 1, 'beta': 2}
>>> SortedDict([('alpha', 1), ('beta', 2)]) == d
True
>>> SortedDict({'alpha': 1, 'beta': 2}) == d
True
>>> SortedDict(alpha=1, beta=2) == d
True
"""
if args and (args[0] is None or callable(args[0])):
_key = self._key = args[0]
args = args[1:]
else:
_key = self._key = None
self._list = SortedList(key=_key)
# Reaching through ``self._list`` repeatedly adds unnecessary overhead
# so cache references to sorted list methods.
_list = self._list
self._list_add = _list.add
self._list_clear = _list.clear
self._list_iter = _list.__iter__
self._list_reversed = _list.__reversed__
self._list_pop = _list.pop
self._list_remove = _list.remove
self._list_update = _list.update
# Expose some sorted list methods publicly.
self.bisect_left = _list.bisect_left
self.bisect = _list.bisect_right
self.bisect_right = _list.bisect_right
self.index = _list.index
self.irange = _list.irange
self.islice = _list.islice
self._reset = _list._reset
if _key is not None:
self.bisect_key_left = _list.bisect_key_left
self.bisect_key_right = _list.bisect_key_right
self.bisect_key = _list.bisect_key
self.irange_key = _list.irange_key
self._update(*args, **kwargs)
@property
def key(self):
"""Function used to extract comparison key from keys.
Sorted dict compares keys directly when the key function is none.
"""
return self._key
@property
def iloc(self):
"""Cached reference of sorted keys view.
Deprecated in version 2 of Sorted Containers. Use
:func:`SortedDict.keys` instead.
"""
# pylint: disable=attribute-defined-outside-init
try:
return self._iloc
except AttributeError:
warnings.warn(
'sorted_dict.iloc is deprecated.'
' Use SortedDict.keys() instead.',
DeprecationWarning,
stacklevel=2,
)
_iloc = self._iloc = SortedKeysView(self)
return _iloc
def clear(self):
"""Remove all items from sorted dict.
Runtime complexity: `O(n)`
"""
dict.clear(self)
self._list_clear()
def __delitem__(self, key):
"""Remove item from sorted dict identified by `key`.
``sd.__delitem__(key)`` <==> ``del sd[key]``
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> del sd['b']
>>> sd
SortedDict({'a': 1, 'c': 3})
>>> del sd['z']
Traceback (most recent call last):
...
KeyError: 'z'
:param key: `key` for item lookup
:raises KeyError: if key not found
"""
dict.__delitem__(self, key)
self._list_remove(key)
def __iter__(self):
"""Return an iterator over the keys of the sorted dict.
``sd.__iter__()`` <==> ``iter(sd)``
Iterating the sorted dict while adding or deleting items may raise a
:exc:`RuntimeError` or fail to iterate over all keys.
"""
return self._list_iter()
def __reversed__(self):
"""Return a reverse iterator over the keys of the sorted dict.
``sd.__reversed__()`` <==> ``reversed(sd)``
Iterating the sorted dict while adding or deleting items may raise a
:exc:`RuntimeError` or fail to iterate over all keys.
"""
return self._list_reversed()
def __setitem__(self, key, value):
"""Store item in sorted dict with `key` and corresponding `value`.
``sd.__setitem__(key, value)`` <==> ``sd[key] = value``
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict()
>>> sd['c'] = 3
>>> sd['a'] = 1
>>> sd['b'] = 2
>>> sd
SortedDict({'a': 1, 'b': 2, 'c': 3})
:param key: key for item
:param value: value for item
"""
if key not in self:
self._list_add(key)
dict.__setitem__(self, key, value)
_setitem = __setitem__
def copy(self):
"""Return a shallow copy of the sorted dict.
Runtime complexity: `O(n)`
:return: new sorted dict
"""
return self.__class__(self._key, list(self.items()))
__copy__ = copy
@classmethod
def fromkeys(cls, iterable, value=None):
"""Return a new sorted dict initailized from `iterable` and `value`.
Items in the sorted dict have keys from `iterable` and values equal to
`value`.
Runtime complexity: `O(n*log(n))`
:return: new sorted dict
"""
return cls((key, value) for key in iterable)
def keys(self):
"""Return new sorted keys view of the sorted dict's keys.
See :class:`SortedKeysView` for details.
:return: new sorted keys view
"""
return SortedKeysView(self)
def items(self):
"""Return new sorted items view of the sorted dict's items.
See :class:`SortedItemsView` for details.
:return: new sorted items view
"""
return SortedItemsView(self)
def values(self):
"""Return new sorted values view of the sorted dict's values.
See :class:`SortedValuesView` for details.
:return: new sorted values view
"""
return SortedValuesView(self)
# if sys.hexversion < 0x03000000:
# def __make_raise_attributeerror(original, alternate):
# # pylint: disable=no-self-argument
# message = (
# 'SortedDict.{original}() is not implemented.'
# ' Use SortedDict.{alternate}() instead.'
# ).format(original=original, alternate=alternate)
# def method(self):
# # pylint: disable=missing-docstring,unused-argument
# raise AttributeError(message)
# method.__name__ = original # pylint: disable=non-str-assignment-to-dunder-name
# method.__doc__ = message
# return property(method)
# iteritems = __make_raise_attributeerror('iteritems', 'items')
# iterkeys = __make_raise_attributeerror('iterkeys', 'keys')
# itervalues = __make_raise_attributeerror('itervalues', 'values')
# viewitems = __make_raise_attributeerror('viewitems', 'items')
# viewkeys = __make_raise_attributeerror('viewkeys', 'keys')
# viewvalues = __make_raise_attributeerror('viewvalues', 'values')
class _NotGiven(object):
# pylint: disable=too-few-public-methods
def __repr__(self):
return '<not-given>'
__not_given = _NotGiven()
def pop(self, key, default=__not_given):
"""Remove and return value for item identified by `key`.
If the `key` is not found then return `default` if given. If `default`
is not given then raise :exc:`KeyError`.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> sd.pop('c')
3
>>> sd.pop('z', 26)
26
>>> sd.pop('y')
Traceback (most recent call last):
...
KeyError: 'y'
:param key: `key` for item
:param default: `default` value if key not found (optional)
:return: value for item
:raises KeyError: if `key` not found and `default` not given
"""
if key in self:
self._list_remove(key)
return dict.pop(self, key)
else:
if default is self.__not_given:
raise KeyError(key)
return default
def popitem(self, index=-1):
"""Remove and return ``(key, value)`` pair at `index` from sorted dict.
Optional argument `index` defaults to -1, the last item in the sorted
dict. Specify ``index=0`` for the first item in the sorted dict.
If the sorted dict is empty, raises :exc:`KeyError`.
If the `index` is out of range, raises :exc:`IndexError`.
Runtime complexity: `O(log(n))`
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> sd.popitem()
('c', 3)
>>> sd.popitem(0)
('a', 1)
>>> sd.popitem(100)
Traceback (most recent call last):
...
IndexError: list index out of range
:param int index: `index` of item (default -1)
:return: key and value pair
:raises KeyError: if sorted dict is empty
:raises IndexError: if `index` out of range
"""
if not self:
raise KeyError('popitem(): dictionary is empty')
key = self._list_pop(index)
value = dict.pop(self, key)
return (key, value)
def peekitem(self, index=-1):
"""Return ``(key, value)`` pair at `index` in sorted dict.
Optional argument `index` defaults to -1, the last item in the sorted
dict. Specify ``index=0`` for the first item in the sorted dict.
Unlike :func:`SortedDict.popitem`, the sorted dict is not modified.
If the `index` is out of range, raises :exc:`IndexError`.
Runtime complexity: `O(log(n))`
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> sd.peekitem()
('c', 3)
>>> sd.peekitem(0)
('a', 1)
>>> sd.peekitem(100)
Traceback (most recent call last):
...
IndexError: list index out of range
:param int index: index of item (default -1)
:return: key and value pair
:raises IndexError: if `index` out of range
"""
key = self._list[index]
return key, self[key]
def setdefault(self, key, default=None):
"""Return value for item identified by `key` in sorted dict.
If `key` is in the sorted dict then return its value. If `key` is not
in the sorted dict then insert `key` with value `default` and return
`default`.
Optional argument `default` defaults to none.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict()
>>> sd.setdefault('a', 1)
1
>>> sd.setdefault('a', 10)
1
>>> sd
SortedDict({'a': 1})
:param key: key for item
:param default: value for item (default None)
:return: value for item identified by `key`
"""
if key in self:
return self[key]
dict.__setitem__(self, key, default)
self._list_add(key)
return default
def update(self, *args, **kwargs):
"""Update sorted dict with items from `args` and `kwargs`.
Overwrites existing items.
Optional arguments `args` and `kwargs` may be a mapping, an iterable of
pairs or keyword arguments. See :func:`SortedDict.__init__` for
details.
:param args: mapping or iterable of pairs
:param kwargs: keyword arguments mapping
"""
if not self:
dict.update(self, *args, **kwargs)
self._list_update(dict.__iter__(self))
return
if not kwargs and len(args) == 1 and isinstance(args[0], dict):
pairs = args[0]
else:
pairs = dict(*args, **kwargs)
if (10 * len(pairs)) > len(self):
dict.update(self, pairs)
self._list_clear()
self._list_update(dict.__iter__(self))
else:
for key in pairs:
self._setitem(key, pairs[key])
_update = update
def __reduce__(self):
"""Support for pickle.
The tricks played with caching references in
:func:`SortedDict.__init__` confuse pickle so customize the reducer.
"""
items = dict.copy(self)
return (type(self), (self._key, items))
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted dict.
``sd.__repr__()`` <==> ``repr(sd)``
:return: string representation
"""
_key = self._key
type_name = type(self).__name__
key_arg = '' if _key is None else '{0!r}, '.format(_key)
item_format = '{0!r}: {1!r}'.format
items = ', '.join(item_format(key, self[key]) for key in self._list)
return '{0}({1}{{{2}}})'.format(type_name, key_arg, items)
def _check(self):
"""Check invariants of sorted dict.
Runtime complexity: `O(n)`
"""
_list = self._list
_list._check()
assert len(self) == len(_list)
assert all(key in self for key in _list)
def _view_delitem(self, index):
"""Remove item at `index` from sorted dict.
``view.__delitem__(index)`` <==> ``del view[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> view = sd.keys()
>>> del view[0]
>>> sd
SortedDict({'b': 2, 'c': 3})
>>> del view[-1]
>>> sd
SortedDict({'b': 2})
>>> del view[:]
>>> sd
SortedDict({})
:param index: integer or slice for indexing
:raises IndexError: if index out of range
"""
_mapping = self._mapping
_list = _mapping._list
dict_delitem = dict.__delitem__
if isinstance(index, slice):
keys = _list[index]
del _list[index]
for key in keys:
dict_delitem(_mapping, key)
else:
key = _list.pop(index)
dict_delitem(_mapping, key)
class SortedKeysView(KeysView, Sequence):
"""Sorted keys view is a dynamic view of the sorted dict's keys.
When the sorted dict's keys change, the view reflects those changes.
The keys view implements the set and sequence abstract base classes.
"""
__slots__ = ()
@classmethod
def _from_iterable(cls, it):
return SortedSet(it)
def __getitem__(self, index):
"""Lookup key at `index` in sorted keys views.
``skv.__getitem__(index)`` <==> ``skv[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> skv = sd.keys()
>>> skv[0]
'a'
>>> skv[-1]
'c'
>>> skv[:]
['a', 'b', 'c']
>>> skv[100]
Traceback (most recent call last):
...
IndexError: list index out of range
:param index: integer or slice for indexing
:return: key or list of keys
:raises IndexError: if index out of range
"""
return self._mapping._list[index]
__delitem__ = _view_delitem
class SortedItemsView(ItemsView, Sequence):
"""Sorted items view is a dynamic view of the sorted dict's items.
When the sorted dict's items change, the view reflects those changes.
The items view implements the set and sequence abstract base classes.
"""
__slots__ = ()
@classmethod
def _from_iterable(cls, it):
return SortedSet(it)
def __getitem__(self, index):
"""Lookup item at `index` in sorted items view.
``siv.__getitem__(index)`` <==> ``siv[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> siv = sd.items()
>>> siv[0]
('a', 1)
>>> siv[-1]
('c', 3)
>>> siv[:]
[('a', 1), ('b', 2), ('c', 3)]
>>> siv[100]
Traceback (most recent call last):
...
IndexError: list index out of range
:param index: integer or slice for indexing
:return: item or list of items
:raises IndexError: if index out of range
"""
_mapping = self._mapping
_mapping_list = _mapping._list
if isinstance(index, slice):
keys = _mapping_list[index]
return [(key, _mapping[key]) for key in keys]
key = _mapping_list[index]
return key, _mapping[key]
__delitem__ = _view_delitem
class SortedValuesView(ValuesView, Sequence):
"""Sorted values view is a dynamic view of the sorted dict's values.
When the sorted dict's values change, the view reflects those changes.
The values view implements the sequence abstract base class.
"""
__slots__ = ()
def __getitem__(self, index):
"""Lookup value at `index` in sorted values view.
``siv.__getitem__(index)`` <==> ``siv[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sd = SortedDict({'a': 1, 'b': 2, 'c': 3})
>>> svv = sd.values()
>>> svv[0]
1
>>> svv[-1]
3
>>> svv[:]
[1, 2, 3]
>>> svv[100]
Traceback (most recent call last):
...
IndexError: list index out of range
:param index: integer or slice for indexing
:return: value or list of values
:raises IndexError: if index out of range
"""
_mapping = self._mapping
_mapping_list = _mapping._list
if isinstance(index, slice):
keys = _mapping_list[index]
return [_mapping[key] for key in keys]
key = _mapping_list[index]
return _mapping[key]
__delitem__ = _view_delitem
# Copyright 2014 - 2019 Grant Jenks
# https://github.com/grantjenks/python-sortedcontainers
from collections import deque
N,Q = list(map(int,input().split()))
d = [(10**10,-1,-1)]
SL = SortedList([])
for i in range(N):
S,T,X = list(map(int,input().split()))
d.append((S-X,1,X))
d.append((T-X,-1,X))
d.sort(key = lambda x:x[0])
d = deque(d)
for i in range(Q):
D = int(eval(input()))
while D >= d[0][0]:
time,event,x = d.popleft()
if event == 1:
SL.add(x)
else:
SL.remove(x)
if SL:
print(SL[0])
else:
print(-1)
| p03033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.