hdu_1009_貪心_換取食品問題

傳送門:http://acm.hdu.edu.cn/showproblem.php?pid=1009

這道題思路是很簡潔的,按照取值從大到小排序,之後依次進行加減。

一開始寫的時候習慣性思維按“return weight<cur.weight"賦值,絕對不應該出現的錯誤。

自己在上算法課寫貪心策略求解的時候,用的是兩個for循環下的冒泡排序,現在看來真是:naive~

代碼如下:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int maxn=1000;
int n,m;
double w[maxn]; //用一個數組來存儲每次所保留的信息
struct room
{
    int quest;
    int need;
    double weight;

    bool operator<(const room& cur) const
    {
        return weight>cur.weight;
    }
}r[maxn];

int main(void)
{
    int i,j,k;
    while(cin>>m>>n)
    {
        if(n==-1&&m==-1) break;
        for(i=0;i<n;i++)
        {
            cin>>r[i].quest>>r[i].need;
            r[i].weight=(double)r[i].quest/r[i].need;
        }
        sort(r,r+n);
        int cnt=0;
        for(i=0;i<n;i++)
        {
            if(m==0) break;
            if(m>r[i].need) {w[cnt]=r[i].quest;m-=r[i].need;cnt++;}  //直接用sum+也可以,但這裏
            else {w[cnt]=r[i].weight*m;m=0;}   //爲了代碼的可複用性,採用依次加和的形式
        }
         double sum=0;
         for(i=0;i<=cnt;i++) sum+=w[i];
        printf("%.3f\n",sum);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章