본문 바로가기
전공공부/코딩테스트

(c++) 프로그래머스 "[1차] 캐시"

by 시아나 2022. 4. 12.

https://programmers.co.kr/learn/courses/30/lessons/17680

 

코딩테스트 연습 - [1차] 캐시

3 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "Jeju", "Pangyo", "Seoul", "NewYork", "LA"] 50 3 ["Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul"] 21 2 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "SanFrancisco", "Seoul", "Ro

programmers.co.kr


나의 코드

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

using namespace std;

int solution(int cacheSize, vector<string> cities) {
    vector<int> indexs;
    vector<string> caches;
    int answer = 0;
    if (cacheSize == 0) return 5 * cities.size();
    for (int i = 0; i < cities.size();i++) {
        transform(cities[i].begin(), cities[i].end(), cities[i].begin(), ::tolower);
        auto index = find(caches.begin(), caches.end(), cities[i]);
        if (index == caches.end()) {
            answer += 5;
            if (indexs.size() < cacheSize) {
                indexs.push_back(i);
                caches.push_back(cities[i]);
            }
            else {
                int m = min_element(indexs.begin(), indexs.end()) - indexs.begin();
                indexs[m] = i;
                caches[m] = cities[i];
            }
        }
        else {
            answer += 1;
            indexs[index - caches.begin()] = i;
        }
    }

    return answer;
}