1033. To Fill or Not to Fill (25)

来源:互联网 发布:java 干10年工资多少 编辑:程序博客网 时间:2024/05/01 19:54

加油事件的贪心选择模拟

#include<iostream>#include<vector>#include<algorithm>typedef struct Station{double dis;double price;bool operator<(const Station& other) const{return dis < other.dis;}}Station;double unit_gas;int FindNeatestCheaperStation(int i, double gas, std::vector<Station>& s){int num = s.size();int min_index = i;for(int j = i+1; j < num && s[j].dis-s[i].dis <= gas*unit_gas; ++j){if(s[j].price < s[min_index].price){min_index = j;break;}}return min_index;}int GetFastestStation(int i, double gas, std::vector<Station>& s){int num = s.size();int max_index = i;for(int j = i+1; j < num && s[j].dis-s[i].dis <= gas*unit_gas; ++j){max_index = j;}return max_index;}int main(){double max_gas, total_dis;int n;while(scanf("%lf%lf%lf%d",&max_gas,&total_dis,&unit_gas,&n)!=EOF){std::vector<Station> sVec(n);for(int i = 0; i < n; ++i)scanf("%lf %lf",&sVec[i].price,&sVec[i].dis);//sort station by distancestd::sort(sVec.begin(), sVec.end());Station vir;vir.dis = total_dis;//add destination as a virtual station in the endsVec.push_back(vir);//algorithm coreif(n==0 || sVec[0].dis > 0)//special caseprintf("The maximum travel distance = 0.00\n");else//greedy now{double remain_gas = 0.0;double cur_money = 0.0;int i;for(i = 0; i < n; ){int index;//1. using remain gas find nearest cheaper stationindex = FindNeatestCheaperStation(i, remain_gas, sVec);if(index != i)//find a station else{//get thereremain_gas -= (sVec[index].dis-sVec[i].dis)/unit_gas;i = index;continue;}//2. using max_gas find nearest cheaper stationindex = FindNeatestCheaperStation(i, max_gas, sVec);if(index != i)//find a station else{//get therecur_money += ((sVec[index].dis-sVec[i].dis)/unit_gas-remain_gas)*sVec[i].price;remain_gas = 0.0;i = index;continue;}//3. get the max_gas and go as far as possibleindex = GetFastestStation(i, max_gas, sVec);if(index != i){//can get some wherecur_money += (max_gas-remain_gas)*sVec[i].price;remain_gas = max_gas-(sVec[index].dis-sVec[i].dis)/unit_gas;i = index;continue;}else {printf("The maximum travel distance = %.2lf\n", sVec[i].dis+max_gas*unit_gas);break;}}//end of greedyif(i == n) printf("%.2lf\n", cur_money);}}return 0; }


 

原创粉丝点击