Koala - 4기

[BOJ] 22252 정보 상인 호석

beans3142 2021. 7. 23. 16:51

각 상인의 이름을 키로 갖고 우선순위 큐를 밸류로 갖는 맵, 딕셔너리를 만들면 되는 문제였습니다.

입력받은 첫 번째 값이 1인지 2인지 한번 나눠주고 그 다음 알맞게 우선순위 큐에 푸시해주고, 큐에 존재하는 원소의 개수보다 지워야 할 값의 개수가 많을 때만 생각해주면 간단했습니다.

 

python

from heapq import heappush,heappop
from sys import stdin
input=stdin.readline

q=int(input())
total=0
shopkeeper={}
for i in range(q):
    order=input().rstrip().split()
    if order[0]=='1':
        try:
            for i in range(3,len(order)):
                heappush(shopkeeper[order[1]],-int(order[i]))
        except:
            shopkeeper[order[1]]=[]
            for i in range(3,len(order)):
                heappush(shopkeeper[order[1]],-int(order[i]))
    else:
        try:
            cnt=int(order[2])
            if len(shopkeeper[order[1]])<=cnt:
                total-=sum(shopkeeper[order[1]])
                shopkeeper[order[1]]=[]
            else:
                for i in range(cnt):
                    total-=heappop(shopkeeper[order[1]])
        except:
            pass

print(total)

 

C++

#include <iostream>
#include <map>
#include <queue>

using namespace std;

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	map<string, priority_queue<long long>> shop;
	long long total=0;
	int q;
	cin >> q;
	for (int i = 0; i < q; i++)
	{
		int n,cnt;
		string name;
		cin >> n >> name >> cnt;
		if (n == 1)
		{
			for (int j = 0; j < cnt; j++)
			{
				int price;
				cin >> price;
				shop[name].push(price);
			}
		}
		else
		{
			while (empty(shop[name]) != 1 && cnt--)
			{
				total += shop[name].top();
				shop[name].pop();
			}
		}
	}
	cout << total;
}

 

최근 푼 문제들은 매웠는데 오랜만에 순한 맛이였습니다. 파이썬과 C++로 풀때의 차이를 보는 것이 흥미로웠던 문제였던 것 같습니다.