
이문제를 처음에
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> people, int limit) {
int answer = 0;
sort(people.begin(), people.end(), less<int>());//오름차순으로 일단 정렬한다.
int iPeopleWeight = 0;
for(int i=0; i<people.size(); i++)
{
iPeopleWeight += people[i];//배당 사람추가(무게 증가);
if(iPeopleWeight <= limit)//사람들 무게 합이 리미트보다 작은경우
{
if((i == people.size()-1) && (iPeopleWeight = people[people.size()-1]))//만약 마지막 사람까지 다 태웠으나 배의 허용치 무게를 도달하지 않은경우 예외처리를 위함이다.
{
answer++;
printf("[ %d / %d 막판종료입니다 ] ",iPeopleWeight, i );
return answer;
}
if(iPeopleWeight+people[i+1] > limit)//사람들 무게 합이 리미트보다 작지만 한명 더 추가하면 초과무게 넘는순간
{
printf("[ %d / %d ]",iPeopleWeight, i );
answer++;//배에 사람들 최대허용치 무게 도달한경우임 배 개수 추가한다.
iPeopleWeight = 0;//다시 시도를 위해서 사람들 무게합 0으로 초기화
}
continue;//계속해서 추가한다.
}
}
}
이렇게 풀다가 다른 case에서 안되서 답을 봤다.
int solution(vector<int> people, int limit) {
int answer = 0; int idx = 0;
sort(people.begin(), people.end(), less<int>());//오름차순으로 일단 정렬한다.
while(people.size()>idx)
{
int iBack = people.back();//제일무거운사람-> 한번 싣고 다음부터 빠진다
people.pop_back();
if(iBack+people[idx] <= limit)//제일 무거운사람 + 제일 가벼운사람 < 리미트 무게
{
answer++;
idx++;//한번싣고 빠지는 제일 무거운사람과 같이 빠진다
printf("두명빠짐/" );
}
else
{
answer++;//제일 무거운사람은 그냥 혼자 싣고 뺀다.
printf("한명빠짐/" );
}
}
return answer;
}
내 풀이의 문제점은 sort 이후 작은것끼리 합쳐서 배 무게를 맞추려고 했다.
제일 무게가 많이 나가는것 + 그 당시의 제일 무게가 적게나가는 조합이 아니라
무게 제일 많이나감 + 무게 둘째로 많이 나감 이런식의 조합을 꾸렸기 때문에 예외 case에서 실패였다.