[프로그래머스] 6주차_복서 정렬하기

박개발·2021년 9월 19일
0

프로그래머스

목록 보기
39/42

문제 푼 날짜 : 2021-09-19

문제

문제 링크 : https://programmers.co.kr/learn/courses/30/lessons/85002

접근 및 풀이

아래의 생각대로 코드를 구현하였다.

  1. 각 선수별로 승률을 구해주고, 승리했을 시에 상대 선수의 몸무게와 비교하여 무게가 더 나가는 선수를 이긴 횟수도 체크해준다.
  2. 각 선수별로 선수 번호, 승률, 더 무거운 복서를 이긴 횟수, 몸무게 정보를 저장해둔다.
  3. 주어진 조건에 맞게 정렬해주고, 정렬된 선수 번호를 return해준다.

코드

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

using namespace std;

struct boxer {
    int num;
    double win_rate;
    int win_big_one;
    int weight;
};

bool cmp(boxer a, boxer b) {
    if (a.win_rate == b.win_rate) {
        if (a.win_big_one == b.win_big_one) {
            if (a.weight == b.weight) {
                return a.num < b.num;
            }
            return a.weight > b.weight;
        }
        return a.win_big_one > b.win_big_one;
    }
    return a.win_rate > b.win_rate;
}

vector<int> solution(vector<int> weights, vector<string> head2head) {
    vector<int> answer;
    int len = weights.size();
    vector<boxer> v;
    
    for (int i = 0; i < len; i++) {
        int total = 0, win = 0, upset = 0;
        for (int j = 0; j < head2head[i].length(); j++) {
            if (head2head[i][j] == 'W') {
                win++;
                total++;
                if (weights[i] < weights[j]) {
                    upset++;
                }
            } else if (head2head[i][j] == 'L') {
                total++;
            } else if (head2head[i][j] == 'N') {
                continue;
            }
        }
        double winRate = (double) win/total;
        if (total == 0) {
            winRate = 0;
        }
        v.push_back({ i + 1, winRate, upset, weights[i] });
    }
    sort(v.begin(), v.end(), cmp);
    
    for (auto b : v) {
        answer.push_back(b.num);
    }
    return answer;
}

결과

피드백

비교적 간단한 문제였다.

profile
개발을 잘하고 싶은 사람

0개의 댓글

관련 채용 정보