👋 프로그래머스 <무지의 먹방 라이브> 풀이 코드 (TIL 231227)
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> food_times, long long k) {
int answer = 0;
int food_nums = food_times.size(); //음식의 개수
vector<int> sorted_times;
sorted_times.resize(food_nums); //food_times가 작은 순서대로 정렬된 vector
copy(food_times.begin(), food_times.end(), sorted_times.begin());
sort(sorted_times.begin(), sorted_times.end());
int min_times_index = 0;
int min_times = sorted_times[min_times_index];
while ( k / min_times >= food_nums) {
for (int i=0; i<food_times.size(); i++) {
if (food_times[i] == 0) continue;
else if (food_times[i] == min_times) {
food_times[i] = 0;
food_nums--;
k -= min_times;
min_times_index++;
} else {
food_times[i] -= min_times;
k-= min_times;
}
}
min_times = sorted_times[min_times_index] - sorted_times[min_times_index-1];
int temp = 0;
long long check = 0;
while (k >= 0) {
if (food_times[temp] != 0) {
food_times[temp]--;
k--;
check += food_times[temp];
}
if (temp == food_times.size()-1) {
if (check < k) {
answer = -1;
break;
}
temp = 0;
}
else temp++;
}
answer = temp;
return answer;
}
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp (pair<int, int> a, pair<int, int> b) {
return a.second < b.second; //pair의 second를 기준으로 오름차순
}
int solution(vector<int> food_times, long long k) {
int answer = 0;
int food_nums = food_times.size(); //음식의 개수
int pre_min = 0; //이전단계의 min_times 값
vector<pair<int, int>> foods;
for (int i=0; i<food_nums; i++) {
foods.push_back(make_pair(food_times[i],i+1)); //first: 먹는데 소요되는 시간, second: 음식의 번호
}
sort(foods.begin(), foods.end()); //먹는 시간을 기준으로 오름차순 정리
for (vector<pair<int, int>>::iterator it=foods.begin(); it != foods.end(); ++it,--food_nums) {
long long spend_times = (long long)(it->first - pre_min) * food_nums;
if (spend_times == 0) continue;
if (spend_times <= k) {
k -= spend_times;
pre_min = it->first;
} else {
k = k % food_nums;
sort(it, foods.end(), cmp);
return (it+k)->second;
}
}
return -1;
}
[문제 출처] https://school.programmers.co.kr/learn/courses/30/lessons/42891
[풀이 참조] https://ansohxxn.github.io/programmers/132/