코딩테스트/프로그래머스
[프로그래머스] 체육복 (C++)
Deff_a
2024. 11. 5. 19:45
문제
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
풀이
- 일부 학생들이 체육복을 도난당함 (lost).
- 일부 학생들은 여벌의 체육복을 가져옴 (reserve).
- 체육복은 바로 앞번호나 뒷번호의 학생에게만 빌려줄 수 있음
- 여벌 체육복이 있는 학생도 도난당했을 수 있으며, 이 경우 다른 학생에게 빌려줄 수 없음
- 체육수업에 참여할 수 있는 학생 수를 최대화하는 것이 목표
- 함수는 체육수업에 참여할 수 있는 최대 학생 수를 반환
어렵지 않은 문제지만, 여벌 체육복을 가져온 학생도 도난당할 수 있다는 점을 잘 생각해야한다.
그리고 lost 벡터가 정렬되지 않을 경우를 생각하여 오름차순 정렬한 후, 탐색을 시작했다.
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
unordered_map <int, int> m;
int solution(int n, vector<int> lost, vector<int> reserve) {
int answer = n;
for(int i = 0; i < reserve.size(); i++)
m[reserve[i]]++;
for(int i = 0; i < lost.size(); i++)
m[lost[i]]--;
sort(lost.begin(), lost.end());
for(int i = 0; i < lost.size(); i++){
if(m[lost[i]] == 0)
continue;
if(m[lost[i] - 1] == 1)
m[lost[i] - 1]--;
else if(m[lost[i] + 1]== 1)
m[lost[i] + 1] --;
else
answer--;
}
return answer;
}