1. 程式人生 > >HDU 1009 FatMouse' Trade (簡單的貪心)

HDU 1009 FatMouse' Trade (簡單的貪心)

Problem Description
FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.
Input


The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1’s. All integers are not greater than 1000.
Output

For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.
Sample Input
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1
Sample Output
13.333
31.500

部分揹包問題,這裡我們可以取走物品的一小部分(也就是可以切割),那麼我們就可以根據 物品的價值/物品的重量 (這個可以根據題目轉換)那麼這一個題目其實就是
根據 食物重量/所需的貓糧 來進行我們的貪心策略。
很容易分析得到,我們需要選擇 食物重量/所需的貓糧 這個比值越大越好的,所以我們需要根據這個來進行排序,然後從上往下選擇食物,直到我們手中的貓糧<0

AC程式碼如下:

#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;

struct wareroom{

    int Jweight;
    int Fpounds;
    bool operator < (const wareroom &ware)
    {
        return double(Jweight)/Fpounds>double(ware.Jweight)/ware.Fpounds;
    }
};
void setroom(int n,wareroom a[])
{
    for(int i=0;i<n;i++)
        cin>>a[i].Jweight>>a[i].Fpounds;
    return ;
}
const int maxn=1e5+5;
wareroom ware[maxn];
int main()
{
    int M,N;
    while(cin>>M>>N && (M!=-1 && N!=-1))
    {
        setroom(N,ware);
        sort(ware,ware+N);
        double JtotalWeight=0;
        for(int i=0;i<N;i++)
        {
            if(M>=ware[i].Fpounds)
            {
                M-=ware[i].Fpounds;
                JtotalWeight+=ware[i].Jweight;
            }
            else if(M<ware[i].Fpounds)
            {

                JtotalWeight+=double(M)/ware[i].Fpounds*ware[i].Jweight;
                break;
            }
        }
        cout<<fixed<<setprecision(3);
        cout<<JtotalWeight<<endl;
    }
    return 0;
}