PAT Grado A-1033 Para llenar o no llenar (25 puntos)

Tema: 1033 Para llenar o no llenar (25 puntos)
Análisis : algoritmo codicioso, similar al algoritmo de Dijkstra (aprender de las ideas de cierto blogger)
Código de referencia
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#define MAX 99999999
typedef long long ll;
using namespace std;
double cmax,m,avg;
int n;
struct sta{
    
    
    double price,dis;
    int id;

};
int cmp(sta s1,sta s2)
{
    
    
    return s1.dis < s2.dis;
}
int main()
{
    
    
    sta s[501];
    cin>>cmax>>m>>avg>>n;
    double max_dis = cmax * avg;
    for(int i = 0;i<n;i++){
    
    
        double x,y;
        cin>>x>>y;//y是距离杭州的距离  m是距离目的地的距离
        s[i].id = i+1;
        s[i].price = x;
        s[i].dis = y;
    }
    s[n].dis = m;
    s[n].price = 0;
    sort(s,s+n,cmp);
    if(s[0].dis != 0){
    
    
        cout<<"The maximum travel distance = 0.00";
        return 0;
    }
    int now = 0;
    double price = 0,now_tank = 0;
    while(now < n)
    {
    
    
        int k = -1;
        int min_price = MAX;
        int flag = 0;
        for(int i = now+1;i<=n && s[i].dis - s[now].dis <= max_dis;i++)
        {
    
    
            if(s[i].price < min_price)
            {
    
    
                min_price = s[i].price;
                k = i;
            }
            if(min_price < s[now].price)
            {
    
    
                flag = 1;break;
            }
        }
        if(k == -1)//没有符合条件的加油站,退出循环
            break;
        double need_tank = (s[k].dis - s[now].dis) / avg;
        if(flag)//在里程内找到比当前加油站更便宜的
        {
    
    
            if(need_tank > now_tank)//去往比当前更便宜的加油站油量不够,则加上需要补上的油
            {
    
    
                price += s[now].price * (need_tank - now_tank);
                now_tank = 0;
            }
            else//足够到达下一个加油站
                now_tank -= need_tank;
        }
        else//没有更便宜的加油站,则在当前加油站加满油
        {
    
    
            price += s[now].price * (cmax - now_tank);
            now_tank = cmax - need_tank;
        }
        now = k;
    }
    if(now == n)
        printf("%.2f",price);
    else
        printf("The maximum travel distance = %.2f",s[now].dis + max_dis);

    return 0;
}


Supongo que te gusta

Origin blog.csdn.net/qq_43567222/article/details/112949421
Recomendado
Clasificación