프로그래머스/1레벨

[프로그래머스/C++] 달리기 경주

Koalitsiya 2023. 6. 29. 12:04
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 조건

  • 이름을 불린 선수는 앞의 선수를 추월
  • 1등인 선수의 이름은 불리지 않음

 

문제 풀이

  1. map에 각 선수의 등수를 저장하고 선수의 이름이 불릴 때마다 pos에 삽입
  2. 두 선수의 순서를 바꿔주고 map에 저장된 각 선수의 등수를 조정
  3. callings.size()만큼 반복 후 players 배열 리턴
#include <string>
#include <vector>
#include <map>

using namespace std;

map<string, int> m;

vector<string> solution(vector<string> players, vector<string> callings) {
    for(int i = 0; i < players.size(); i++)
        m[players[i]] = i;
    
    for(int i = 0; i < callings.size(); i++) {
        string temp = "";
        int pos = m[callings[i]];
      
        m[players[pos]]--;
        
        temp = players[pos];
        players[pos] = players[pos - 1];
        players[pos - 1] = temp;
        
        m[players[pos]]++;
    }
    
    return players;
}