홍시홍의 프로그래밍

[프로그래머스] 베스트앨범 본문

알고리즘 문제풀이/프로그래머스

[프로그래머스] 베스트앨범

홍시홍 2020. 4. 10. 01:29

분류 : 해쉬

 

요구사항

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

  1. 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
  2. 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
  3. 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.

풀이

1. 가장 많이 재생된 장르 구하기

2. 장르 내에서 많이 재생된 노래 -> 재생 횟수가 같다면 고유번가 낮은 노래

 

1번은 map사용하여 중복된 string을 더 하여서 총 재생 횟수를 구한다

2번은 vector로 정렬한다

 

뭔가 두번 생각해야하는 문제 인듯하다

 

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

using namespace std;

struct go {
    string str;
    int index;
};
struct vv {
    string str;
    int num;
    int index;
};

bool com(go a, go b) {
    if (a.index > b.index) return true;
    return false;
}
bool com1(vv a, vv b) {
    if (a.num > b.num) return true;
    else if (a.num == b.num) {
        if (a.index < b.index) return true;
    }
    return false;
}
vector<int> solution(vector<string> genres, vector<int> plays) {
    vector<int> answer;
    map<string, int> test;
    map<string, int> ans;
    vector<vv> v;
    //string 별로 변호를 매겨주자
    int num = 1;
    for (int i = 0; i < genres.size(); i++) {
        string nowstr = genres[i];
        int nownum = plays[i];
        v.push_back({ nowstr,nownum ,i});
        if (test[nowstr] == 0) {
            test[nowstr] += nownum;
        }
        else {
            test[nowstr] += nownum;
        }
    }
    vector<go> temp;
    for (auto i = test.begin(); i != test.end(); i++) {
        temp.push_back({ i->first, i->second });
    }

    //내가 원하는 순서를 얻었다.
    sort(temp.begin(), temp.end(), com);
    sort(v.begin(),v.end(),com1);
    int count = 0;
    for (int i = 0; i < temp.size(); i++) {
        string tempstr = temp[i].str;
        int cnt = 0;
        for (int j = 0; j < v.size(); j++) {
            if (tempstr == v[j].str) {
                answer.push_back(v[j].index);
                cnt++;
                count++;
            }
            if (cnt == 2)
                break;
        }
    }

    return answer;
}
int main() {

}
Comments