본문 바로가기

c++/프로그래머스

프로그래머스 : 베스트앨범 C++

programmers.co.kr/learn/courses/30/lessons/42579

 

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

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

programmers.co.kr

풀이

1) 장르당 총 재생횟수를 구하자, genre랑 play의 크기는 동일함

2) map을 value값에 대해 정리하려면 벡터에 옮겨야된다!!

 -> key값에 대해 정렬하려면 map <int, int, greater<int> >a; 선언할때 이렇게

 

3) 옮겼으면 정렬

 

4) 이제 1등. 2등 두개를 play 벡터를 탐색하면서 정하기

 

5) 장르에 속한 노래가 한곡인 경우도 있으니 예외처리!

 

코드

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

using namespace std;

bool cmp(pair<string,int> a, pair<string,int> b)
{
    return (a.second > b.second) ; //내림차순!!
}

vector<int> solution(vector<string> genres, vector<int> plays) {
    vector<int> answer;
    map<string,int> maps;
    
    for(int i=0;i<genres.size();i++)
    {
        maps[genres[i]] += plays[i]; //장르별 재생횟수 다 더하기
    }
    
    vector<pair<string,int> > data(maps.begin(),maps.end());
    
    sort(data.begin(),data.end(),cmp);
    
    for(int i=0;i<data.size();i++)//장르별
    {
        int first_index=0; int first_value=0;
        int second_index=0; int second_value=0;
        for(int y=0;y<genres.size();y++)
        {
            if(data[i].first==genres[y])//원하는 장르
            {
                if(plays[y]>first_value)//현재 1위보다 재생 수 많을때
                {
                    second_index = first_index;
                    second_value = first_value;//기존 1등은 2등으로!
                    first_index = y;
                    first_value = plays[y];
                }
                else if(plays[y]>second_value)//2위보다 재생 수 많을때
                {
                    second_index = y;
                    second_value = plays[y];
                }
            }
        }
        answer.push_back(first_index);
        //장르에 속하는 곡이 1곡일 수도 있음
        if(second_value !=0)
        {
             answer.push_back(second_index);
        }
    }
    return answer;
}