1. 程式人生 > 實用技巧 >超市(stl + 貪心)

超市(stl + 貪心)

連結

按照過期時間從小到大排序(兩個元素一組可以用pair,放在 vector裡面,排序)

當前商品的個數 > 過期時間,把利潤最小的替換出去(小根堆)

#include <bits/stdc++.h>
#define int long long
using namespace std;
int n;
priority_queue<int,vector<int>,greater<int>> heap;//小根堆
signed main(){
    //freopen("in","r",stdin);
    ios::sync_with_stdio(0
); while(cin >> n){ vector<pair<int,int>> p(n); for(int i = 0; i < n;i++) cin >> p[i].second >> p[i].first;//利潤和過期時間,將時間排序 sort(p.begin(),p.end()); for(auto x : p){ heap.push(x.second);//把利潤存進去 while(heap.size() >= x.first)//
商品個數 大於等於 過期天數,題目說一天只能賣一個 heap.pop();//出佇列 } int res = 0; while(heap.size()) res += heap.top(), heap.pop(); cout << res << endl; } return 0; }
View Code