Protecting the Flowers

Farmer John went to cut some wood and left N (2 ≤ N ≤ 100,000) cows eating the grass, as usual. When he returned, he found to his horror that the cluster of cows was in his garden eating his beautiful flowers. Wanting to minimize the subsequent damage, FJ decided to take immediate action and transport each cow back to its own barn.
Each cow i is at a location that is Ti minutes (1 ≤ Ti ≤ 2,000,000) away from its own barn. Furthermore, while waiting for transport, she destroys Di (1 ≤ Di ≤ 100) flowers per minute. No matter how hard he tries, FJ can only transport one cow at a time back to her barn. Moving cow i to its barn requires 2 × Ti minutes (Ti to get there and Ti to return). FJ starts at the flower patch, transports the cow to its barn, and then walks back to the flowers, taking no extra time to get to the next cow that needs transport.
Write a program to determine the order in which FJ should pick up the cows so that the total number of flowers destroyed is minimized.
Input
Line 1: A single integer N
Lines 2… N+1: Each line contains two space-separated integers, Ti and Di, that describe a single cow’s characteristics
Output
Line 1: A single integer that is the minimum number of destroyed flowers
Sample Input
6
3 1
2 5
2 3
3 2
4 1
1 6
Sample Output
86

题意:有n头牛跑到花园里吃花,它们分别在距离牛圈T分钟处吃花,并且每分钟会吃掉D朵花。
现在要把这些牛赶回牛圈,但每次只能赶一头牛,来回时间是2*T。被赶回的牛不能吃花,而其他牛会继续吃花。求花的最小损失量。

题目分析:
这是一道经典的贪心问题,首先我们要确定排序准则:

假设在赶a和b(t表示赶牛花费的时间,d表示牛吃花的速度)牛时已经花费了时间x。
那么先赶a所损失的花数为(只考虑这两头牛)x*a.d+(x+a.t)*b.d
先赶b牛所损失的花数为x*b.d+(x+b.t)*a.d
如果x*a.d+(x+a.t)*b.d<x*b.d+(x+b.t)*a.d,那么先赶a牛的损失更少,
即先赶a牛最优。
当只有这两头牛时(即x=0)得到:a.t*b.d<b.t*a.d。这就是排序准则。

得到了排序准则后,我们就可以直接算出最少的花损失量了。

代码如下:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <algorithm>
#include <iomanip>
#define LL long long
const int N=1e5+5;
using namespace std;
struct Node{        //定义结构体表示牛
	int t,d;
}a[N];
bool cmp(Node a,Node b)
{
	return a.t*b.d<a.d*b.t; //排序准则
}
int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cin>>a[i].t>>a[i].d;
		a[i].t*=2;          //因为赶牛的时间是2T,所以要将输入的t乘2
	}
	sort(a,a+n,cmp);
	LL ans=0,sum=0;         //结果有可能爆int,要用long long
	for(int i=0;i<n;i++)
	{
		ans+=sum*a[i].d;    //算出结果即可
		sum+=a[i].t; 
	}
	cout<<ans<<endl;
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lwz_159

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值