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

YH J·2023년 5월 18일
0

프로그래머스

목록 보기
87/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/178871

내 풀이

질문하기에 있는 힌트를 보고 풀었다. player, rank 순서의 map
rank, player순서의 map를 만들고 초기 players값을 넣어준다.
callings를 for문을 돌리면서 나온 player와 그 앞에 위치한 player의 랭크와 이름을 스왑해준다.

내 코드

#include <string>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

vector<string> solution(vector<string> players, vector<string> callings) {
    vector<string> answer;
    
    map<string, int> pr;
    map<int, string> rp;
    
    for(int i = 0; i < players.size(); i++)
    {
        pr[players[i]] = i;
        rp[i] = players[i];
    }
    string swap1;
    string swap2;
    int a;
    int b;
    for(const auto& c : callings)
    {
        a = pr[c] - 1;
        b = pr[c];
        swap1 = rp[a];
        swap2 = rp[b];
        
        rp[b] = swap1;
        rp[a] = swap2;
        
        pr[swap1] = b;
        pr[swap2] = a;
    }
    
    for(int i = 0; i < players.size(); i++)
        answer.push_back(rp[i]);
    
    return answer;
}

다른 사람의 풀이

#include <map>
#include <string>
#include <vector>
#include <iostream>

using namespace std;

vector<string> solution(vector<string> players, vector<string> callings)
{
    vector<string> answer;

    map<string, int> m;
    for(int i=0; i<players.size(); i++)
        m[players[i]]=i;


    int s1, s2;
    string tmp;
    for(int i=0; i<callings.size(); i++)
    {
        s2=m[callings[i]]; s1=s2-1;
        m[players[s2]]--; m[players[s1]]++;
        //cout << s1 << " " << s2 << endl;
        tmp=players[s2];
        players[s2]=players[s1];
        players[s1]=tmp;
    }

    answer=players;

    return answer;
}

다른 사람의 풀이 해석

굳이 컨테이너를 2개로 하지 않고 string,int map만 만들어서 players를 넣어주고
callings 원소에 따라 map에서의 순위를 바꿔준 뒤 해당 바뀐 내용을 players에 바로 바로 적용시켜준다.

profile
게임 개발자 지망생

0개의 댓글