HDU 1070 [Milk] 贪心

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1070

题目大意:要选择买牛奶,小明每天喝200ml,生产6天后的牛奶不喝,少于200ml的会扔掉。

关键思想:简单的结构体排序,我们要找性价比最高的(可用天数/价格),如果相同就V最大的。据此写个结构体排序贪心即可。

代码如下:

#include <iostream>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;

const int MAXN=105;

struct milk{
    string brand;
    int V;
    float DP;
    milk(){}
    milk(string a,int b,float c):brand(a),V(b),DP(c){}
}have[MAXN];

bool cmp(milk a,milk b){
    return a.DP==b.DP?a.V>b.V:a.DP>b.DP;
}


int main(){
    int T,N;
    cin>>T; 
    while(T--){
        //memset(have,0,sizeof(have)); 用memset会出BUG! 
        cin>>N;
        int P,day;
        for(int i=0;i<N;i++){
            cin>>have[i].brand>>P>>have[i].V; 
            if(have[i].V>1000)day=5;
            else day=have[i].V/200;
            if(day==0)have[i]=milk{};
            else have[i].DP=1.0*day/P;
        }
        sort(have,have+N,cmp);
        cout<<have[0].brand<<endl;
    }
    return 0;
}
#include <iostream>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;

const int MAXN=105;

struct milk{
    string brand;
    int V;
    float DP;
    milk(){}
    milk(string a,int b,float c):brand(a),V(b),DP(c){}
}have[MAXN];

bool cmp(milk a,milk b){
    return a.DP==b.DP?a.V>b.V:a.DP>b.DP;
}


int main(){
    int T,N;
    cin>>T; 
    while(T--){
        //memset(have,0,sizeof(have)); 用memset会出BUG! 
        cin>>N;
        int P,day;
        for(int i=0;i<N;i++){
            cin>>have[i].brand>>P>>have[i].V; 
            if(have[i].V>1000)day=5;
            else day=have[i].V/200;
            if(day==0)have[i]=milk{};
            else have[i].DP=1.0*day/P;
        }
        sort(have,have+N,cmp);
        cout<<have[0].brand<<endl;
    }
    return 0;
}

 

    原文作者:哇咔咔咔
    原文地址: https://www.cnblogs.com/G-M-WuJieMatrix/p/7435200.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞