机试指南第二章-经典入门-贪心例题自解

例2.11 FatMouse's Trade

解题思路

贪心策略。每次都买剩余物品中性价比(即重量价格比)最高的物品,直到该物品被买完或者钱耗尽。若该物品已经被买完,则我们继续在剩余的物品中寻找性价比最高的物品

AC代码

#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
", ans);
    }
    //system("pause");
    return 0;
}

例2.12 今年暑假不AC

解题思路 

在选择第x(x>=1)个节目时, 一定是选择在收看完前x-1个节目后,其它所有可以收看节目中结束时间最早的 节目,这就是我们要找的贪心策略。在每次选择节目时,都不断的利用这种贪心策略,我们就能完成最优解的求解。 

AC代码

#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
", ans);
    }
    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/yun-an/p/11129460.html