Leetcode1705. 吃苹果的最大数目[C++题解]:贪心
生活随笔
收集整理的這篇文章主要介紹了
Leetcode1705. 吃苹果的最大数目[C++题解]:贪心
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 本題思路
- 補充知識priority_queue優先隊列的使用
題目鏈接:1705. 吃蘋果的最大數目
本題思路
本題復述:共n天,給定每天新產生蘋果的數目和這些蘋果的過期時間。每天最多只能吃1個蘋果,問n天最多吃多少個蘋果。
策略:貪心,每次吃最早過期的蘋果。
用小根堆來維護當前可以吃的蘋果的集合。但是不是盲目地存放,而是把同一天產生的蘋果用一個pair來表示,(timeLast, count),其中timeLast表示最后可以吃的時間(腐爛時間的前一天),count表示這一天產生的蘋果的數量。然后按照過期時間來維護小根堆。
每次吃的時候,在最早過期的那堆蘋果里選擇一個吃。
for循環遍歷的是可以吃到蘋果的天數, 因為n小于等于20000,而且每天可以產生的蘋果最多也是20000,每天最多吃一個,所以最壞的情況是遍歷40000天。
ac代碼
class Solution { public:int eatenApples(vector<int>& apples, vector<int>& days) {const int MaxApple=40000;//最多40000天可以吃蘋果typedef pair<int,int> PII;priority_queue<PII, vector<PII>,greater<PII> > heap;int res=0;int n=apples.size();for(int i=0;i<MaxApple;i++){if(i<n && apples[i]>0)//入堆heap.push({i+days[i]-1,apples[i] });// 最后可以吃的時間 和 蘋果數量//蘋果過期了,不能吃,出堆while(!heap.empty()&&heap.top().first<i) heap.pop();if(heap.empty() ) continue;//吃蘋果并出堆auto t=heap.top();heap.pop();res++;if(--t.second) //沒吃完,重新加回堆里heap.push(t);}return res;} };補充知識priority_queue優先隊列的使用
優先隊列容器默認是大根堆,即每次訪問的都是最大值。
priority_queue<float> q; //默認大根堆 priority_queue<float,vector<float>, greater<float>> q; //小根堆寫法 #include<bits/stdc++.h>using namespace std;int main(){priority_queue<float> q; //默認大根堆 //insert three elements into the priority queueq.push(66.6);q.push(22.2);q.push(44.4);cout<<q.top()<<" ";q.pop();cout<<q.top()<<endl;q.pop();//insert three more elementsq.push(11.1);q.push(55.5);q.push(33.3);//skip one elementq.pop(); //刪除最大的 //pop and print remaining elementswhile(!q.empty()){cout<<q.top()<<" ";q.pop();}cout<<endl; }大根堆輸出結果
小根堆的輸出結果
priority_queue<float,vector<float>, greater<float>> q; //默認大根堆總結
以上是生活随笔為你收集整理的Leetcode1705. 吃苹果的最大数目[C++题解]:贪心的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode861翻转矩阵后的得分(
- 下一篇: 优先队列如何按照pair 的第二关键字排