挑战程序设计竞赛 第2章习题 poj 3262 Protecting the Flowers 比率贪心

地址  http://poj.org/problem?id=3262

题意

牛每秒钟吃Di的花朵,将牛赶回家需要时间Ti(来回时间乘以2)
询问以最优的次序将牛赶回家,损失的花朵数量。

输入 第一行输入一个数字N  下面输入N行数字  每行有两个空格隔开的数字表示一头牛赶回家需要的时间T和每秒吃掉的花朵D

输出一个数字   以最优的次序将牛赶回家,损失的花朵数量

解法 

比率贪心

假设两头牛AB 赶回家的时间为TA 和TB ,每秒钟吃掉的花朵为DA和DB

如果先赶A牛回家  那么损失就是  DB*TA*2

如果先赶B牛回家  那么损失就是  DA*TB*2

我们需要赶损失较大的牛回家才能减少损失

那么将所有的牛 两两比较排序 比较函数为

struct ELE {
    int t;
    int d;
}ele[N];
int n;

bool cmp(const struct ELE& a, const struct ELE& b) {
    return (a.d * b.t) > (b.d * a.t);
}

按照该次序赶牛回家 计算损失

// 1123555.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;
/*
6
3 1
2 5
2 3
3 2
4 1
1 6
*/
struct ELE {
    int t;
    int d;
}ele[N];
int n;

bool cmp(const struct ELE& a, const struct ELE& b) {
    return (a.d * b.t) > (b.d * a.t);
}

int main()
{
    cin >> n;
    long long destroy = 0;
    long long ans = 0;
    for (int i = 0; i < n; i++) {
        cin >> ele[i].t >> ele[i].d;
        destroy+= ele[i].d;
    }

    sort(ele,ele+n,cmp);

    for (int i = 0; i < n; i++) {
        destroy -= ele[i].d;
        ans += destroy * ele[i].t * 2;
    }

    cout << ans << endl;


    return 0;
}
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/14587123.html