[C++] 프로그래머스 Level 2 : 구명보트

Kim Nahyeong·2022년 9월 25일
0

프로그래머스

목록 보기
29/38

#include <string>
#include <vector>
#include <algorithm> // sort
#include <iostream>

using namespace std;

int solution(vector<int> people, int limit) {
    int answer = 0;
    int start = 0;
    
    sort(people.begin(), people.end()); // 오름차순 정렬
    
    while(start < people.size()){
        int back = people.back(); // vector 제일 끝 back으로 알 수 있음.
        people.pop_back(); // vector pop 가능
        
        if(people[start] + back <= limit){
            answer++;
            start++; // 앞 사람도 같이 태우기
        } else {
            answer++; // 뒷 사람만 혼자 타기
        }
    }
    
    return answer;
}

이런게 그리디지,,, 한 3시간동안 '조이스틱' 문제 삽질하다가 (아무리 생각해도 그리디 문제 아닌 것 같음) 그래서 구명보트 문제를 대신 풀기 시작했다.

그냥 정렬해서 제일 마른 사람이랑 같이 태울 수 있으면 태우고 아니면 구명보트를 혼자 타면 된다. 이게 진짜 Level 2 그리디 문제지... ㅠㅠ

0개의 댓글