[백준] 나는야 포켓몬 마스터 이다솜 #1620

welchs·2022년 1월 29일
0

알고리즘

목록 보기
23/44
post-thumbnail

설명

index로는 바로 배열의 요소에 접근할 수 있지만 poketmon의 이름으로는 바로 인덱스를 알려면 검색을 해야 한다. 바로 알 수 있도록 해쉬맵 자료구조를 사용하면 된다.
JS의 경우 Map을 사용해도 되지만 기본으로 제공하는 객체에 해당 인덱스를 담아서 답을 구했다.

c++ 배운 함수들: isdigit, atoi, stoi, unordered_map

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');

const [N, M] = input[0].split(' ').map(Number);
const poketmons = input.slice(1, 1 + N);
const problems = input.slice(1 + N);

const solution = (N, poketmons, problems) => {
  let answer = ``;
  const poketmonMap = {};
  poketmons.forEach((poketmon, idx) => {
    poketmonMap[poketmon] = idx + 1;
  });
  problems.forEach((problem) => {
    if (/[0-9]/.test(problem)) {
      answer += poketmons[problem - 1];
    } else {
      answer += poketmonMap[problem];
    }
    answer += '\n';
  });
  return answer;
};

console.log(solution(N, poketmons, problems));

C++ 풀이

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int N, M; 
    cin >> N >> M;
    unordered_map<string, string> pokemon;
    unordered_map<string, string> pokemonSeq;
    
    for (int i=0; i<N; i++) {
        string str;
        cin >> str;
        pokemon.insert({str, to_string(i+1)});
        pokemonSeq.insert({to_string(i+1), str});
    }
    for (int i=0; i<M; i++) {
        string problem;
        cin >> problem;
        if (isdigit(problem[0])) {
            cout << pokemonSeq[problem] << '\n';
        } else {
            cout << pokemon[problem] << '\n';
        }
    }
    return 0;
}
profile
고수가 되고 싶은 조빱

0개의 댓글