杭電oj--1070(貪心演算法)
阿新 • • 發佈:2018-11-23
1. Ignatius will never drink the milk which is produced 6 days ago or earlier. That means if the milk is produced 2005-1-1, Ignatius will never drink this bottle after 2005-1-6(inclusive).
要點分析:1.牛奶是一次性買的 2.低於200ml的牛奶將被捨棄,一天都不夠喝(程式中可設定其價效比為999999999) 3.每200ml喝一天,最多喝5天,也就是做多喝1000ml,超過5天的牛奶將會被捨棄 4.如果價效比相同,選容量大的品牌 |
#include<iostream> #include<string> using namespace std; typedef struct milk{ char brand[120]; int price; int v; double cost; }MILK; void compare(MILK *m,int len){//比較函式 MILK tmp,max; int i,j; for(i=0;i<len;i++){//計算價效比 if(m[i].v<200){//低於200ml,設定價效比為99999999999 m[i].cost=99999999999; continue; } if(m[i].v>1000)//超過1000ml,就用價格 除以5天 m[i].cost=m[i].price/double(5); else 反之,就用價格 除以可以喝多少天的天數 m[i].cost=(double)m[i].price/(m[i].v/200); } for(i=1;i<=len;i++)//按照價效比升序排列 for(j=0;j<len-i;j++) if(m[j].cost>m[j+1].cost){ tmp=m[j]; m[j]=m[j+1]; m[j+1]=tmp; } max=m[0]; for(i=1;i<len;i++) if(max.cost==m[i].cost) if(max.v<=m[i].v) max=m[i];//若價效比相同找容量最高的 cout<<max.brand<<endl; } int main(){ int n,kinds,i,max,t; MILK m[120]; while(cin>>n){ while(n--){ cin>>kinds; for(i=0;i<kinds;i++) cin>>m[i].brand>>m[i].price>>m[i].v; compare(m,kinds);//比較 } break; } return 0; }