機試指南第二章-經典入門-貪心例題自解

例2.11 FatMouse's Tradephp

解題思路ios

貪心策略。每次都買剩餘物品中性價比(即重量價格比)最高的物品,直到該物品被買完或者錢耗盡。若該物品已經被買完,則咱們繼續在剩餘的物品中尋找性價比最高的物品spa

AC代碼code

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

struct Thing
{
    double j;
    double f;
    double s;//性價比
}t[1000];

bool cmp(Thing a, Thing b)
{
    return a.s > b.s;
}

int main()
{
    double m;
    int n;
    while (scanf("%lf%d", &m, &n) != EOF)
    {
        if (m == -1 && n == -1)break;
        for (int i = 0; i < n; i++)
        {
            scanf("%lf%lf", &t[i].j, &t[i].f);
            t[i].s = t[i].j / t[i].f;
        }
        sort(t, t + n, cmp);
        int id = 0;
        double ans = 0;
        while (m > 0 && id < n)
        {
            if (m > t[id].f)
            {
                ans += t[id].j;
                m -= t[id].f;
            }
            else
            {
                ans += t[id].j*m / t[id].f;
                m = 0;
            }
            id++;
        }
        printf("%.3lf\n", ans);
    }
    //system("pause");
    return 0;
}

例2.12 今年暑假不ACblog

解題思路 get

在選擇第x(x>=1)個節目時, 必定是選擇在收看完前x-1個節目後,其它全部能夠收看節目中結束時間最先的 節目,這就是咱們要找的貪心策略。在每次選擇節目時,都不斷的利用這種貪心策略,咱們就能完成最優解的求解。 string

AC代碼it

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

struct Thing
{
    int beg;
    int end;
}t[100];

bool cmp(Thing a, Thing b)
{
    return a.end < b.end;
}

int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
    {
        if (n == 0)break;
        for (int i = 0; i < n; i++)scanf("%d%d", &t[i].beg, &t[i].end);
        sort(t, t + n, cmp);
        int cur = 0, ans = 0;//當前時間和節目總數
        for (int i = 0; i < n; i++)
        {
            if (cur <= t[i].beg)
            {
                cur = t[i].end;
                ans++;
            }
        }
        printf("%d\n", ans);
    }
    //system("pause");
    return 0;
}
相關文章
相關標籤/搜索