1+ #include < bits/stdc++.h>
2+
3+ using namespace std ;
4+
5+ bool compare (pair<int , int > a, pair<int , int > b) {
6+ return a.second < b.second ;
7+ }
8+
9+ int solution (vector<int > food_times, long long k) {
10+ // 전체 음식을 먹는 시간보다 k가 크거나 같다면 -1
11+ long long summary = 0 ;
12+ for (int i = 0 ; i < food_times.size (); i++) {
13+ summary += food_times[i];
14+ }
15+ if (summary <= k) return -1 ;
16+
17+ // 시간이 작은 음식부터 빼야 하므로 우선순위 큐를 이용
18+ priority_queue<pair<int , int > > pq;
19+ for (int i = 0 ; i < food_times.size (); i++) {
20+ // (음식 시간, 음식 번호) 형태로 우선순위 큐에 삽입
21+ pq.push ({-food_times[i], i + 1 });
22+ }
23+
24+ summary = 0 ; // 먹기 위해 사용한 시간
25+ long long previous = 0 ; // 직전에 다 먹은 음식 시간
26+ long long length = food_times.size (); // 남은 음식의 개수
27+
28+ // summary + (현재의 음식 시간 - 이전 음식 시간) * 현재 음식 개수와 k 비교
29+ while (summary + ((-pq.top ().first - previous) * length) <= k) {
30+ int now = -pq.top ().first ;
31+ pq.pop ();
32+ summary += (now - previous) * length;
33+ length -= 1 ; // 다 먹은 음식 제외
34+ previous = now; // 이전 음식 시간 재설정
35+ }
36+
37+ // 남은 음식 중에서 몇 번째 음식인지 확인하여 출력
38+ vector<pair<int , int > > result;
39+ while (!pq.empty ()) {
40+ int food_time = -pq.top ().first ;
41+ int num = pq.top ().second ;
42+ pq.pop ();
43+ result.push_back ({food_time, num});
44+ }
45+ sort (result.begin (), result.end (), compare); // 음식의 번호 기준으로 정렬
46+ return result[(k - summary) % length].second ;
47+ }
0 commit comments