Study hard

(c++)프로그래머스 코딩테스트 연습-체육복 본문

프로그래머스/탐욕법(Greedy)

(c++)프로그래머스 코딩테스트 연습-체육복

Nimgnoej 2021. 3. 20. 12:13

programmers.co.kr/learn/courses/30/lessons/42862

 

코딩테스트 연습 - 체육복

점심시간에 도둑이 들어, 일부 학생이 체육복을 도난당했습니다. 다행히 여벌 체육복이 있는 학생이 이들에게 체육복을 빌려주려 합니다. 학생들의 번호는 체격 순으로 매겨져 있어, 바로 앞번

programmers.co.kr

[풀이]

vector<int>student에 각 학생이 가지고 있는 체육복 개수를 저장하고, 체육복이 없는 학생이고 앞 또는 뒤 학생이 2개의 체육복을 가지고 있을 경우 각각 +1, -1을 해주었다.

마지막에 1개 이상의 체육복을 가진 학생 수를 세 출력하였다.

#include <string>
#include <vector>

using namespace std;

int solution(int n, vector<int> lost, vector<int> reserve) {
    int answer = 0;
    vector<int>student(n+1,1);//각 학생의 체육복 개수
    for(int i=0;i<lost.size();i++)
        student[lost[i]]--;
    for(int i=0;i<reserve.size();i++)
        student[reserve[i]]++;
    for(int i=1;i<=n;i++){
        if(student[i]!=0)
            continue;
        if(i!=1&&student[i-1]==2){
            student[i]++;
            student[i-1]--;
        }
        else if(i!=n&&student[i+1]==2){
            student[i]++;
            student[i+1]--;
        }
        
    }
    for(int i=1;i<=n;i++){
        if(student[i]!=0)
            answer++;
    }
    return answer;
}