알고리즘/C++
[C++] 프로그래머스 체육복 (탐욕법(Greedy))
지휘리릭
2020. 2. 25. 17:48
#include <algorithm>
#include <vector>
using namespace std;
int solution(int n, vector<int> lost, vector<int> reserve) {
int answer = 0;
vector<int> student(n+1);
int i;
for(i=0;i<lost.size();i++) { student[lost[i]] -= 1; }
for(i=0;i<reserve.size();i++) { student[reserve[i]] += 1; }
for(i=0;i<lost.size();i++){
// 내가 도난당했지만, 여분 체육복이 있는 경우
if(student[lost[i]] == 0){ continue;}
// 앞번호 친구가 여분 체육복 있는지
else if(student[lost[i]-1] == 1){
student[lost[i]] += 1;
student[lost[i]-1] -=1;
}
// 뒷번호 친구가 여분 체육복 있는지
else if(student[lost[i]+1] == 1){
student[lost[i]] += 1;
student[lost[i]+1] -= 1;
}
}
for(i=1;i<student.size();i++){
if(student[i] >= 0){
answer = answer + 1;
}
}
return answer;
}