Written by JS970
on
on
1620 - 나는야 포켓몬 마스터 이다솜
- 난이도: 실버 4
- 날짜: 2023년 2월 27일
- 상태: Correct/Retry
- 추가 검토 여부: No
- 알고리즘 : map
solution
- 한동안 마주치지 않아서 endl의 사용이 시간초과를 야기한다는 것을 간과했다. 이 때문에 많이 틀렸다.
- 기본적으로 map 자료구조를 사용해서 해결할 수 있는 문제이다.
- 숫자를 key값으로 하는 map과 문자열을 key값으로 가지는 map두 개를 선언해서 문제를 해결했다.
- unordered_map을 사용하면 map을 사용했을 때보다 살짝 빠르게 문제 풀이가 가능하다. 두 자료구조 모두 제한시간 안에 풀이 가능하다.
- string헤더에서 제공하는 isdigit()함수를 사용하는 법을 기억하도록 하자
code
- unordered_map사용 코드
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N, M;
cin >> N >> M;
unordered_map<int, string> arr_name;
unordered_map<string, int> arr_num;
for(int i = 1; i <= N; i++)
{
string name;
cin >> name;
arr_name[i] = name;
arr_num[name] = i;
}
string * ans = new string[M];
for(int i = 0; i < M; i++)
cin >> ans[i];
for(int i = 0; i < M; i++)
{
if(isdigit(ans[i][0]))
{
auto res = arr_name.find(stoi(ans[i]));
cout << res->second << endl;
}
else
{
auto res = arr_num.find(ans[i]);
cout << res->second << endl;
}
}
return 0;
}
- map 사용 코드
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N, M;
cin >> N >> M;
map<int, string> arr_name;
map<string, int> arr_num;
for(int i = 1; i <= N; i++)
{
string name;
cin >> name;
arr_name[i] = name;
arr_num[name] = i;
}
string * ans = new string[M];
for(int i = 0; i < M; i++)
cin >> ans[i];
for(int i = 0; i < M; i++)
{
if(isdigit(ans[i][0]))
{
if(arr_name.find(stoi(ans[i])) != arr_name.end())
cout << arr_name[stoi(ans[i])] << '\n';
}
else if(arr_num.find(ans[i]) != arr_num.end())
cout << arr_num[ans[i]] << '\n';
}
return 0;
}