[프로그래머스] [C++] 베스트앨범 (map)

2021. 3. 31. 10:10알고리즘/프로그래머스

1. 문제

 

코딩테스트 연습 - 베스트앨범 | 프로그래머스 (programmers.co.kr)

 

코딩테스트 연습 - 베스트앨범

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가

programmers.co.kr

 

 

2. map 

3개의 map으로 문제를 해결할 수 있다.

 

1. 장르 -> 해당 장르 노래의 모든 플레이 횟수

 

2. 장르 -> 해당 장르에서 플레이 횟수 가 가장 많은 두개의 노래 인덱스

 

3. 1 번을 뒤집은 map

 

 

장르 중에서 가장 큰 것을 먼저 선택해야하므로

      1번 map에서 3번 map 으로의 변환이 필요하다.

그 장르 속에서 가장 큰것 두개를 선택해야하므로

      2번 map 이 필요하다 

 

3번 map을 end부터 begin 까지 2에 대입하면서 모든 원소를 집어 넣으면 문제가 해결된다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <string>
#include <vector>
#include <map>
 
using namespace std;
 
void pushBack(map<stringvector<int> >& mp, string& str, int idx, vector<int>& plays) {
    mp[str].push_back(idx);
 
    for(int i = mp[str].size() - 1; i >= 1; i--) {
        if(plays[mp[str][i]] > plays[mp[str][i-1]]) 
            swap(mp[str][i], mp[str][i-1]);
    }
 
    if(mp[str].size() == 3)
        mp[str].pop_back();
}
 
vector<int> solution(vector<string> genres, vector<int> plays) {
    vector<int> answer;
 
    map<stringint> genresToCount;
    map<stringvector<int> > genresToPlays;
    map<intstring> countToGenres;
 
    for(int i = 0; i < genres.size(); i++) {
        genresToCount[genres[i]] += plays[i];
        pushBack(genresToPlays, genres[i], i ,plays);
    }
 
    for(auto it = genresToCount.begin(); it != genresToCount.end(); it++) {
        countToGenres[it->second] = it->first;
    }
 
    for(auto it = countToGenres.end(); it-- != countToGenres.begin(); ) {
        for(int j = 0; j < genresToPlays[it->second].size(); j++)
            answer.push_back(genresToPlays[it->second][j]);
    }
    return answer;
}
cs