https://www.acmicpc.net/problem/2243
2243번: 사탕상자
첫째 줄에 수정이가 사탕상자에 손을 댄 횟수 n(1 ≤ n ≤ 100,000)이 주어진다. 다음 n개의 줄에는 두 정수 A, B, 혹은 세 정수 A, B, C가 주어진다. A가 1인 경우는 사탕상자에서 사탕을 꺼내는 경우이
www.acmicpc.net
문제 접근
세그먼트 트리로 구현했다.
구간 합에서 개수를 파악하고 좌측과 우측중 어디로 이동할지 판별하면 된다.
현재 노드에서 자식노드중 좌측의 크기보다 현재 접근하려는 개수가 더많으면 우측으로 이동하면 된다.
시간 메모리도 잘나왔고 1트에 코드도 엄청 짧게나와서 만족스럽다
코드
import sys
import math
input = sys.stdin.readline
"""
2243
"""
def getOut(count, index):
while index<node:
index*=2
if tree[index]<count:
count -= tree[index]
index += 1
print(index-node)
update(index-node, -1)
def update(target, val):
index = node + target
tree[index] += val
while index>1:
index //= 2
tree[index] = tree[index*2] + tree[index*2+1]
n = int(input())
node = 2** math.ceil(math.log2(1000000))
tree = [0] * (node*2+1)
for _ in range(n):
ABC = list(map(int,input().split()))
if ABC[0] == 1:
getOut(ABC[1], 1)
else:
update(ABC[1],ABC[2])
'백준 > 문제풀이_python' 카테고리의 다른 글
18436 수열과 쿼리 37 python (0) | 2024.02.05 |
---|---|
10999 구간 합 구하기 2 python (0) | 2024.02.04 |
2024 구간 합 구하기 python (0) | 2024.02.02 |
13537 수열과 쿼리 1 python (0) | 2024.02.01 |
14427 수열과 쿼리 15 (0) | 2024.01.31 |
댓글