๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค (์‹คํŒจ์œจ, 2019 KAKAO BLIND RECRUITMENT) C++

by UKHYUN22 2022. 1. 3.
728x90

 

 ์นด์นด์˜ค ๋ฌธ์ œ๋กœ vector๊ฐ€ ์ฃผ์–ด์ง€๋Š” ๊ฒฝ์šฐ ๊ฑฐ์˜ ์ด์ค‘ for๋ฌธ์œผ๋กœ ์‹œ์ž‘ํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ๋งŽ์€ ๊ฒƒ ๊ฐ™๋‹ค. ์˜ค๋žœ๋งŒ์— ์ฃผ์„์„ ๋จผ์ € ๋‹ฌ๊ณ  ์ฝ”๋“œ๋ฅผ ์งฐ๋Š”๋ฐ ์ƒ๊ฐ๋ณด๋‹ค ์ž˜ ์งœ์กŒ๋‹ค. Map์„ ํ™œ์šฉํ•ด์„œ value์— ๋Œ€ํ•ด ์˜ค๋ฆ„์ฐจ์ˆœ/๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜๋Š” ๋ฒ•์„ ์ฒดํ™”ํ•œ ๊ฒƒ ๊ฐ™๋‹ค.

 

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

using namespace std;


bool cmp(const pair<int, double>& a, const pair<int, double>& b) {
    // value๊ฐ€ ๊ฐ™๋‹ค๋ฉด key์— ํ•ด๋‹นํ•˜๋Š” ๊ฒƒ์€ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค.
    if(a.second == b.second) return a.first < b.first;
    
    // value์— ๋Œ€ํ•ด ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค.
    else return a.second > b.second;
}

vector<int> solution(int N, vector<int> stages) {
    vector<int> answer;
    map<int, double> fail_ratio;
    int challenger = stages.size();
    int failer = 0;
    
    for(int j = 1 ; j <= N ; j++) {
        for(int i = 1 ; i <= stages.size() ;i++) {
            // ํ•ด๋‹น stage๋ฅผ ๋งŒ๋‚˜๋ฉด ๋ช‡ ๋ช…์ด ๋„์ „์„ ํ–ˆ๊ณ  ๋ช‡ ๋ช…์ด ์‹คํŒจํ–ˆ๋Š”์ง€ ์ฒดํฌํ•œ๋‹ค.
            if(stages[i-1] == j) 
                failer++;
        }
        
        // ๋ชจ๋“  ๋„์ „์ž๊ฐ€ stage๊ฐ€ ๋๋‚˜๊ธฐ ์ „์— ์—†์–ด์ง€๋Š” ๊ฒฝ์šฐ 0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์œผ๋ฏ€๋กœ
        if(challenger == 0)
            fail_ratio[j] = 0;
        else
            // map ๋ณ€์ˆ˜์— key๋Š” stage, value๋Š” ์‹คํŒจ์œจ์„ ๋‹ด์•„์ค€๋‹ค.
            fail_ratio[j] = (double) failer / (double) challenger;

        challenger -= failer;
        failer = 0;
    }
    
    // map์˜ value์— ํ•ด๋‹นํ•˜๋Š” ๊ฒƒ์„ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๊ธฐ ์œ„ํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜
    vector<pair<int,double>> temp (fail_ratio.begin(), fail_ratio.end());
    sort(temp.begin(), temp.end(), cmp);
    
    for(auto cnt : temp){
        cout << cnt.first << " " << cnt.second << endl;
        answer.push_back(cnt.first);
    }
    
    return answer;
}