Chapter II machine test Guide - Getting the classic - self-greedy examples

例2.11 FatMouse's Trade

Problem-solving ideas

Greedy strategy. Always buy the remaining items in the cost (ie, the price weight ratio) up items until the items are buying or the money runs out. If the item has been buying, we continue to look for cost-effective items in the remaining items

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;
}

Example 2.12 this summer without AC

Problem-solving ideas 

In the choice of x (x> = 1) a program, it must be selected after x-1 before watching a program finished, you can watch all the other programs in the end time of the first program, this is what we are looking for greedy strategy. Each time the program is chosen, the constant use of this greedy strategy, we can finish solving the optimal solution. 

AC Code

#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;
}

 

Guess you like

Origin www.cnblogs.com/yun-an/p/11129460.html