1. 程式人生 > >貪心--金銀島

貪心--金銀島

一、演算法分析

     典型的貪心演算法,思路是:計算每個金屬的價效比,然後根據價效比進行排序,從高到低儘可能塞入揹包,揹包滿則得到最大值。

二、參考程式碼

#include "iostream"  

#include "iomanip"  

#include "algorithm"  

using namespace std;  

struct metal  

{  

    double w;  

    double v;  

    double price;  

}a[201];  

double comp(metal a1,metal a2)  

{  

    return

 a1.price>a2.price;  

}  

int main()  

{  

    int k;  

    cin>>k;  

    while(k--)  

    {  

        double result=0;  

        double w;  

        int s;  

        cin>>w>>s;  

        double tempW,tempV;  

        for(int i=0;i<s;i++)  

        {  

            cin>>tempW>>

tempV;  

            a[i].w = tempW;  

            a[i].v = tempV;  

            a[i].price = tempV/tempW;  

        }  

        sort(a,a+s,comp);  

        for(int i=0;i<s;i++)  

        {  

            if(w>=a[i].w)  

            {  

                result+=a[i].v;  

                w-=a[i].w;

  

            }else   //考慮w裝下所有金屬並有空餘  

            {  

                result+=w*a[i].price;  

                break;  

            }  

        }  

        cout<<fixed<<setprecision(2)<<result<<endl;  

    }  

}