문제

https://www.acmicpc.net/problem/1620

 

1620번: 나는야 포켓몬 마스터 이다솜

첫째 줄에는 도감에 수록되어 있는 포켓몬의 개수 N이랑 내가 맞춰야 하는 문제의 개수 M이 주어져. N과 M은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수인데, 자연수가 뭔지는 알지? 모르면

www.acmicpc.net

풀이

  • unordered_map은 해쉬 테이블로 구현한 자료구조로 탐색 시간 복잡도는 O(1)입니다.
  • map은 Binary Search Tree로 탐색 시간 복잡도는 O(log n)입니다.

저는 2개의 unordered_map을 선언하여 string,int를 구분지어서 만들었습니다.

조심해야 할 점은 count() 선언을 까먹지 말고 써주지 않고 직접 배열을 찾는 방식 (num [i]) 은 그 자체로 노드가 선언되므로 count()를 사용합시다!

코드

#include<iostream>
#include<vector>
#include<unordered_map>
#include<queue>
#include<string>
using namespace std;
int N, M;
unordered_map<string, int> st;
unordered_map<int,string> num;
int main() {
	cin >> N >> M;

	for (int i = 1; i <= N; i++) {
		string a;
		cin >> a;
		st.insert({ a,i });
		num.insert({ i,a });

	}
	vector<string>result;
	//M입력찾기
	for (int j = 0; j < M; j++) {
		
		string arr;
		cin >> arr;
		
		if (arr[0] < 'A') { //숫자라면
			if (num.count(stoi(arr))>0) {
				result.push_back(num[stoi(arr)]);
			}
		}
		else { //영어 
			if (st.count(arr) > 0) {
				result.push_back(to_string(st[arr]));
			}
		}
		

	}

	for (int i = 0; i < result.size(); i++) {
		cout << result[i] << '\n';
	}

	return 0;
}

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

[백준] 상어 초등학교 (21608/C++)  (0) 2022.03.12
[백준] 통계학 (2108/C++)  (0) 2022.02.02
[백준] 경로 찾기 (11403/C++)  (0) 2022.01.30
[백준] 최대 힙 (11279/C++)  (0) 2022.01.26
[백준] 최소 힙 (1927/C++)  (0) 2022.01.26

+ Recent posts