贪心算法

4 篇文章 0 订阅

贪心算法

* 简单贪心算法初探
  • * T1:有m元钱,那种商品,每种物品的重量为weight,总价值为price,可以使用0到price的任意价格购买相应多的物品,要求输出m元最多能买到多少物品
#include <iostream>
#include <algorithm>
using namespace std;

typedef struct goods 
{
    double weight;  //商品的重量
    double price;   //商品的总价值
    double cost;        //商品的性价比
    bool operator < (const goods &A) const          //">" 不能重载
    {
        return cost > A.cost;
    }
};

int main()
{
    double m;               //钱
    int n;
    while (cin >> m >> n)
    {
        if (m == -1 && n == -1)
            break;
        goods buf[1000];
        for (int i = 0; i < n; i++)
        {

            cin >> buf[i].weight >> buf[i].price;
            buf[i].cost = buf[i].weight / buf[i].price;
        }
        sort(buf, buf+n);
        int idx = 0;
        double result = 0;
        while (idx < n && m > 0)
        {
            if (m > buf[idx].price)
            {
                result = result + buf[idx].weight;
                m -= buf[idx].price;
                idx++;
            }

            else
            {
                result += buf[idx].cost * m;
                idx++;
                m = 0;
            }
        }
        cout << result << endl;
    }
    system("pause");
    return 0;
}
  • T2: “今年暑假不AC?”“是的。”“那你干什么呢?”“看世界杯呀,笨蛋!”“@#¥%……&*%。。。”确实如此,世界杯来了,球迷的节目也来了,估计很多ACMer也会抛开计算机,奔向电视作为球迷,一定想看尽量多的完整比赛,当然,作为新时代的好青年,你一定还会看一些其他的节目,比如新闻联播(永远不要忘记关心国家大事)、非常6+1、中国新歌声、以及《开心辞典》等,假设你已经知道了所有你喜欢看的电视节目的转播时间表,你会合理安排吗?(目标是能看尽量多的完整节目)

    输入:输入数据包含多个测试实例,每个测试实例的第一行只有一个完整整数n(n<=100),表示你喜欢看的节目的总数,然后是n行数据,每行包括两个数据i_starttime,i_endtime(1<=i<=n),分别表示第i个节目的开始和结束时间,为了简化问题,每个时间都用一个正整数表示。n=0表示输入结束,不作处理。

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

typedef struct project 
{
    int starttime;          //节目的开始时间
    int endtime;            //节目的结束时间
    bool operator < (const project &A) const 
    {
        return endtime < A.endtime;
    }
};

int main()
{
    int num;
    while (cin >> num)
    {
        if (num == 0)
            break;
        project pro[100];
        for (int i = 0; i < num; i++)
        {
            cin >> pro[i].starttime >> pro[i].endtime;
        }
        sort(pro, pro + num);           //按照结束时间进行相应的排序
        int result = 1;
//      int *test = new int[num];
        int idx = 0;
        for (int i = 1; i < num; i++)
            if (pro[i].starttime >= pro[idx].endtime)       //后面节目的开始时间不能比当前节目的结束时间早
            {
                result++;
                idx = i;
            }
        cout << result << endl;
    }
    system("pause");
    return 0;
}

未完待续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值