• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
dwtfukgv
博客园    首页    新随笔    联系   管理    订阅  订阅
HDU 1009 FatMouse' Trade (贪心算法)

题意:就是老鼠要用猫粮换粮食,第i个房间一些东西,要用东西去换,可以不全换。问给定的猫粮最多能换多少粮食。

析:贪心算法。我们先算出来每个房间物品的平均价格是多少,肯定越低越好,并且如果能全换就全换,如果不能,

肯定是最后一次了,就把剩下全部换了,看看能换多少。求和。

代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstring>
#include <map>
#include <cctype>

using namespace std;
struct node{
    double ave;   int x, y;
    node() { }
    node(int xx, int yy) : x(xx), y(yy), ave((double)xx/(double)yy) { }
    bool operator < (const node &p) const {
        return ave > p.ave;
    }
};
node a[1005];

int main(){
    int n, m;
    while(~scanf("%d %d", &n, &m) && (m+n != -2)){
        int x, y;
        for(int i = 0; i < m; ++i){
            scanf("%d %d", &x, &y);
            a[i] = node(x, y);
        }

        sort(a, a+m);
        double ans = 0.0;
        for(int i = 0; i < m; ++i){
            if(n >= a[i].y){ ans += a[i].x;  n -= a[i].y;  }
            else if(!n)  break;
            else{
                ans += a[i].ave * n;
                n = 0;
            }
        }
        printf("%.3lf\n", ans);
    }
    return 0;
}

 

posted on 2016-06-02 18:34  dwtfukgv  阅读(265)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3