leetcode 857 (堆)

    科技2022-07-10  110

    // class Solution { // public: // double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int K) { // int N=wage.size(); // double ans=DBL_MAX; // for(int i=0;i<N;i++){ // double res=wage[i]; // vector<double> prices; // for(int j=0;j<N;j++){ // if(j==i) continue; // double tmp=quality[j]/double(quality[i])*wage[i]; // if(wage[j]<=tmp){ // prices.push_back(tmp); // } // } // sort(prices.begin(),prices.end()); // if(prices.size()<K-1) continue; // for(int i=0;i<K-1;i++){ // res+=prices[i]; // } // // if(i==0) ans=res; // // cout<<res<<endl; // ans=min(ans,res); // } // return ans; // } // }; bool cmp( vector<double> &a,vector<double> &b){ return a[0]<b[0]; } bool cmp1( vector<double> &a, vector<double> &b){ return a[1]<b[1]; } class Solution{ public: double mincostToHireWorkers(vector<int>&quality,vector<int>&wage,int K){ vector<vector<double>> worker(quality.size(),{0.0,0.0}); for(int i=0;i<quality.size();i++){ worker[i][0]=wage[i]/(double)quality[i]; worker[i][1]=quality[i]; } sort(worker.begin(),worker.end(),cmp); //or(auto w:worker)cout<<w[0]<<" "<<w[1]<<endl; double res; priority_queue<double,vector<double>,less<int>>q; double qual=0.0; for(int i=0;i<worker.size();i++){ q.push(worker[i][1]); qual+=worker[i][1]; if(q.size()==K) res=qual*worker[i][0]; if(q.size()>K){ qual-=q.top(); q.pop(); res=min(res,qual*worker[i][0]); } } return res; // priority_queue<vector<int>,vector<vector<int>>,decltype(cmp1) *>q(cmp1); // priority_queue<vector<double>,vector<vector<double>>,decltype (cmp1) *>q(cmp1); // double qua; // double res; // for(vector<double> w:worker){ // cout<<w[0]<<" "<<w[1]<<endl;// 没有这条语句答案是错的 // q.push({w[0],w[1]}); // qua+=w[1]; // if(q.size()==K){ // res=qua*w[0]; // cout<<res<<endl; // } // if(q.size()>K){ // qua-=q.top()[1]; // res=min(res,qua*w[0]); // q.pop(); // } // } } };
    Processed: 0.011, SQL: 8