"the only way to be truly satisfied is to do what you believe is great work."

[C++/Python] 백준 13414 : 수강신청

해쉬 테이블을 이용하는 문제였다.

해쉬테이블에, 학번을 key로 , 수강신청 순서를 value로 저장한다.
이것을 수강신청 순서에대해 정렬 한 후 제한인원만큼 출력하면 되는데,
제한인원보다 수강신청 인원이 적은경우를 예외처리 해주어야 한다.

[C++]

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;


bool compare(pair<string, int>& a, pair<string, int>& b) {
	if (a.second <= b.second) {
		return true;
	}
	else {
		return false;
	}
}


int main() {
	int N, M;
	cin >> N >> M;

	unordered_map <string, int> hash;

	string S;
	for (int i = 0; i < M; i++) {
		cin >> S;
		hash[S] = i;
	}

	vector<pair<string, int>> ordered_hash;

	for (auto student : hash) {
		ordered_hash.push_back(student);
	}

	sort(ordered_hash.begin(), ordered_hash.end(), compare);


	for (int i = 0; i < min(N, (int)ordered_hash.size()) ; i++) {
		cout << ordered_hash[i].first << "\n";
	}


}

 

[Python]
python에서의 해쉬테이블은 dictionary를 활용한다.

N,M = map(int,(input().split()))
hash = {}
for i in range(M):
    hash[str(input())] = i

sorted_hash = sorted(hash.items(), key = lambda x : x[1])

for i in range(N):
    if (i < len(sorted_hash)):
        print(sorted_hash[i][0])
    else:
        break

 

'알고리즘 > 백준' 카테고리의 다른 글

[C++] 14940 : 쉬운 최단거리  (0) 2024.08.12
[C++] 백준 2210 : 숫자판 점프  (0) 2024.02.13
[C++] 백준 1021 : 회전하는 큐  (1) 2024.02.07
[C++] 백준 2223 : 금화  (0) 2024.02.06
[C++] 백준 17087 : 숨바꼭질 6  (0) 2024.01.29