https://www.acmicpc.net/problem/1620
백준 1620번: 나는야 포켓몬 마스터 이다솜
맵을 써본 적이 없어서 벡터로 해결하려고 난리치다가 시간 제한에 걸리는 바람에 엄청 헤맸다.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int pokemon, question;
string temp;
vector<pair<int, string>>dic;
cin >> pokemon >> question;
for (int i = 0; i < pokemon; i++)
{
cin >> temp;
dic.push_back({ i + 1, temp });
}
for (int i = 0; i < question; i++)
{
cin >> temp;
if (temp[0] >= 65 && temp[0] <= 90)
{
for (int j = 0; j < pokemon; j++)
{
if (dic[j].second == temp)
{
cout << dic[j].first << "\n";
break;
}
}
} // 이름 들어옴, 숫자 찾기
else
{
cout << dic[stoi(temp) - 1].second << "\n";
} //숫자 들어옴
}
}
벡터로 해결해보려고 노력했던 코드. 의도한 출력이 나오긴 한다.
find를 사용했어도 find의 내부는 for문이기 때문에 시간 초과가 나오는 건 똑같았을 것이다.
결국 map을 사용하여 해결...
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int pokemon, question;
string temp;
int numTemp;
map<string, int> nameDic;
map<int, string> numDic;
cin >> pokemon >> question;
for (int i = 0; i < pokemon; i++)
{
cin >> temp;
nameDic.insert({ temp, i + 1 });
numDic.insert({ i + 1, temp });
}
for (int i = 0; i < question; i++)
{
cin >> temp;
if (temp[0] >= 65 && temp[0] <= 90)
{
cout << nameDic[temp] << "\n";
} //이름 들어옴, 숫자 찾기
else
{
numTemp = stoi(temp);
cout << numDic[numTemp] << "\n";
} //숫자 들어옴, 이름 찾기
}
}
key로 value를 찾는 건 가능한데, for문을 사용하지 않고 value로 key를 찾는 방법은 없을까?
value로 key가 찾고 싶어서 또 한참 방황하다가 결국
<string, int> 맵 하나, <int, string> 맵 하나, 이렇게 두 개를 사용하는 것으로 해결했다.
도움을 받은 글
https://life-with-coding.tistory.com/305
[C++][STL] map 사용법 정리
인트로 안녕하세요. 오늘은 C++ STL 연관 컨테이너 중 하나인 map에 대해 알려드리겠습니다. 목차 1) Map이란? 2) Map 기본 형태 3) Map 정렬 4) Map 사용방법 - 헤더 포함 - map 선언 - search : map에서 데이터
life-with-coding.tistory.com
https://psh50zmfhtm.tistory.com/m/5
[C++] map과 unordered_map
기본적으로 map과 unordered_map은 key, value의 한 쌍으로, pair 형태를 띄는 자료구조입니다. map map은 아래와 같은 형태의 RB Tree로 이루어져 있습니다. (이해하는 데 도움을 받은 링크를 첨부합니다.) 요
psh50zmfhtm.tistory.com
'백준' 카테고리의 다른 글
[백준] 10814번: 나이순 정렬 (0) | 2023.01.14 |
---|---|
[백준] 2108번: 통계학 (0) | 2023.01.08 |
[백준] 4948번: 베르트랑 공준 (0) | 2022.12.19 |
[백준] 1193번: 분수찾기 (C++) (0) | 2022.12.08 |
[백준] 1018번: 체스판 다시 칠하기 (C++) (0) | 2022.03.29 |