-
[프로그래머스] 캐시 c++Coding Test/programmers 2023. 5. 2. 09:54728x90
문제 설명
지도개발팀에서 근무하는 제이지는 지도에서 도시 이름을 검색하면 해당 도시와 관련된 맛집 게시물들을 데이터베이스에서 읽어 보여주는 서비스를 개발하고 있다.
이 프로그램의 테스팅 업무를 담당하고 있는 어피치는 서비스를 오픈하기 전 각 로직에 대한 성능 측정을 수행하였는데, 제이지가 작성한 부분 중 데이터베이스에서 게시물을 가져오는 부분의 실행시간이 너무 오래 걸린다는 것을 알게 되었다.
어피치는 제이지에게 해당 로직을 개선하라고 닦달하기 시작하였고, 제이지는 DB 캐시를 적용하여 성능 개선을 시도하고 있지만 캐시 크기를 얼마로 해야 효율적인지 몰라 난감한 상황이다.어피치에게 시달리는 제이지를 도와, DB 캐시를 적용할 때 캐시 크기에 따른 실행시간 측정 프로그램을 작성하시오.
제한 사항
- 캐시 교체 알고리즘은 LRU(Least Recently Used)를 사용한다.
- cache hit일 경우 실행시간은 1이다.
- cache miss일 경우 실행시간은 5이다.
https://school.programmers.co.kr/learn/courses/30/lessons/17680
풀이
이 문제의 포인트는 LRU입니다.
Least Recently Used : 가장 오랫동안 참조되지 않은 페이지를 교체하는 기법입니다.
참조가 된 city를 메모리에서 삭제 후 맨 뒤에 삽입 해야합니다. 그래야 참조 최신성을 유지할 수 있습니다.
deque, queue, stack 자료구조는 C++에서는 contains같은 함수가 없어서 container에 city가 있는지 확인해야 합니다.
#include <string> #include <vector> #include <deque> #include <algorithm> using namespace std; int solution(int cacheSize, vector<string> cities) { int answer = 0; deque<string> dq; for(string& city : cities){ transform(city.begin(), city.end(), city.begin(), ::tolower); bool hit = false; int index = 0; for(index = 0; index < dq.size(); index++){ if(dq[index] == city){ hit = true; break; } } dq.push_back(city); if(hit){ dq.erase(dq.begin() + index); answer += 1; } else{ if(dq.size() > cacheSize){ dq.pop_front(); } answer += 5; } } return answer; }
728x90'Coding Test > programmers' 카테고리의 다른 글
[프로그래머스] 여행경로 c++ (0) 2023.05.23 [프로그래머스] 기능개발 c++, java (0) 2023.05.06 [프로그래머스] 연속 펄스 부분 수열의 합 c++ (0) 2023.03.16 [프로그래머스] N으로 표현 c++ (0) 2023.03.16 [프로그래머스] 덧칠하기 c++ (0) 2023.03.11