[BOJ 1202] ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ, ์ฐ์ ์์ ํ์ ํ
https://www.acmicpc.net/problem/1202
1202๋ฒ: ๋ณด์ ๋๋
์ฒซ์งธ ์ค์ N๊ณผ K๊ฐ ์ฃผ์ด์ง๋ค. (1 ≤ N, K ≤ 300,000) ๋ค์ N๊ฐ ์ค์๋ ๊ฐ ๋ณด์์ ์ ๋ณด Mi์ Vi๊ฐ ์ฃผ์ด์ง๋ค. (0 ≤ Mi, Vi ≤ 1,000,000) ๋ค์ K๊ฐ ์ค์๋ ๊ฐ๋ฐฉ์ ๋ด์ ์ ์๋ ์ต๋ ๋ฌด๊ฒ Ci๊ฐ ์ฃผ์ด์ง๋ค. (1 ≤ Ci
www.acmicpc.net
์ค๋ต ์ฝ๋
import sys
sys.setrecursionlimit(1000000)
def FastInput():
return sys.stdin.readline().rstrip()
def BinarySearch(array, target):
if len(array) == 0:
return None
left = 0
right = len(array)-1
while left <= right:
mid = (left + right)//2
if array[mid] == target:
return mid
elif array[mid] < target:
left = mid + 1
else:
right = mid - 1
if array[mid] < target:
if mid == len(array)-1:
return None
return mid+1
else:
return mid
jewel_num, bag_num = map(int, FastInput().split())
jewel_list=[]
for i in range(jewel_num):
jewel_weight , jewel_price = map(int, FastInput().split())
jewel_list.append((jewel_price, jewel_weight))
bag_storage_list = []
for i in range(bag_num):
bag_max_weight = int(FastInput())
bag_storage_list.append(bag_max_weight)
jewel_list.sort()
jewel_list.reverse()
bag_storage_list.sort()
total_price = 0
for jewel_price, jewel_weight in jewel_list:
appro_bag_idx = BinarySearch(bag_storage_list, jewel_weight)
if appro_bag_idx == None:
continue
total_price += jewel_price
# del(bag_storage_list[appro_bag_idx])
bag_storage_list = bag_storage_list[:appro_bag_idx] + bag_storage_list[appro_bag_idx+1:]
print(total_price)
#๋ฆฌ์คํธ๊ฐ ์์ฒญ ํด ๋ ์ผํ์ ์ธ ์๊ณ ๋ฆฌ์ฆ์ ๋ฐ๋ณต์ ์ผ๋ก ์ํํ๊ธฐ ์ํด, del ๊ฐ์ ํจ์๋ฅผ ๊ณ์ ์ฌ์ฉํ๋ ๊ฒ์ ์ง๋์น๊ฒ ์ฐ์ฐ์ด ๋ง์์ง๋ค.
๊ฐ์ฅ ๋น์ผ ๋ณด์๋ถํฐ ์ต๋ํ ์์ ๊ฐ๋ฐฉ์ ๋ฃ์ด๋ณด๋ ๋ฐฉ์์ด๋ค.
๊ธฐ๋ณธ์ ์ธ ์ค๊ณ ์์ฒด๋ ์๊ฐ๋ณต์ก๋๊ฐ ํฌ์ง ์์ ๋ณด์์ผ๋
์ ๋ ฌ๋ ๋ฆฌ์คํธ์์ ์์๋ฅผ ํ๋์ฉ ์ ๊ฑฐํ๋ ๊ณผ์ ์ ๋ฐ๋ณตํ๋ ๊ฒ์ด ์๊ฐ์ด๊ณผ๋ฅผ ์ผ๊ธฐํ๋ค.
del ํจ์์ ๊ฒฝ์ฐ O(n)์ ์๊ฐ๋ณต์ก๋๋ฅผ ๊ฐ์ง๊ณ ์์ด, ๋ถ์ ์ ํ์๋ค.
ํ์ ํ์ฉํ ์ฐ์ ์์ ํ๋ฅผ ํตํด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๊ฒ์ด ๋ชจ๋ฒ๋ต์์ด์๋ค.
๋ชจ๋ฒ๋ต์
import sys
import heapq
input = sys.stdin.readline
n, k = map(int, input().split())
items = []
bag = []
candi = []
answer = 0
for _ in range(n):
# ๋ณด์ ๋ฌด๊ฒ ๊ธฐ์ค ์ต์ ํ ์ฝ์
heapq.heappush(items, list(map(int, input().split())))
for _ in range(k):
bag.append(int(input()))
# ๊ฐ๋ฐฉ ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
bag = sorted(bag)
for cap in bag:
# ๊ฐ๋ฐฉ ์์๊ฑฐ ๋ถํฐ ๊บผ๋ด๋ฉด์ ๊ทธ ๊ฐ๋ฐฉ์ ๋ค์ด๊ฐ๋ ๋ณด์์ผ๋จ ๋ค ๊บผ๋.
# ๊บผ๋ด์ ๊ฐ์ ๊ธฐ์ค์ผ๋ก ์ต๋ํ์ ๋ฃ์
while items and items[0][0] <= cap:
heapq.heappush(candi, -heapq.heappop(items)[1])
# candi์ ํ์ฌ ๊ฐ๋ฐฉ์ ๋ค์ด๊ฐ ์ ์๋ ๋ณด์ ๋ค๋ค์ด์์.(์ต๋ํ)
# ์ด ์ค ํ๋ ๋นผ๋ฉด ๋จ.
if candi:
answer += abs(heapq.heappop(candi))
print(answer)
ํ ์๋ฃ๊ตฌ์กฐ๋ฅผ ํ์ฉํ์ฌ ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ์ ๊ตฌํํ์๋ค.
๋ํ ๋ด ํ์ด์ ๋ฌ๋ฆฌ ๊ฐ์ฅ ๋น์ผ ๋ณด์์ ๊ฐ์ฅ ๊ฐ๋ฒผ์ด ๊ฐ๋ฐฉ์ ๋ฃ๋๊ฒ์ด ์๋๋ผ ๊ฐ์ฅ ๊ฐ๋ฒผ์ด ๊ฐ๋ฐฉ์ ๊ฐ์ฅ ๋น์ผ ๋ณด์์ ๋ฃ๋ ๋ฐฉ์์ผ๋ก ์ค๊ณํ์๋ค.
Feedback
- ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ์ ํ ๋ ์ ๊ทผ ๋ฐฉ์์ ๋ค๊ฐ์ ์ผ๋ก ๊ณ ๋ฏผํ์
- ์ค๋ฆ์ฐจ์, ๋ด๋ฆผ์ฐจ์์ผ๋ก ์์ ์ ์ํํ ๋, ํ ์๋ฃ๊ตฌ์กฐ์ ์ฌ์ฉ์ผ๋ก del ํจ์์ ์์กดํ๋ ์ํฉ์ ํผํ ์ ์์์ ๊ธฐ์ตํ์.