Protecting the Flowers
直接中文
Descriptions
FJ去砍树,然后和平时一样留了 N (2 ≤ N ≤ 100,000)头牛吃草。当他回来的时候,他发现奶牛们正在津津有味地吃着FJ种的美丽的花!为了减少后续伤害,FJ决定立即采取行动:运输每头牛回到自己的牛棚。 每只奶牛i在离牛棚Ti(1 ≤ Ti ≤ 2,000,000) 分钟路程的地方,每分钟吃掉Di(1 ≤ Di ≤ 100)朵花。FJ使尽浑身解数,也只能一次带回一头奶牛。弄回一头奶牛i需要2*Ti分钟(来回)。由于怕被怼,从FJ决定带回i号奶牛开始,i号奶牛就不会吃花。请你找出被毁坏的花的最小数量 .
Input
第一行:
N
第 2.. N+1: 第i+1行是Ti和Di,
第 2.. N+1: 第i+1行是Ti和Di,
Output
Line 1: 被毁坏花的最少数量。保证结果在64位整数范围内
Sample Input
6 3 1 2 5 2 3 3 2 4 1 1 6
Sample Output
86
Hint
FJ的顺序是: 6, 2, 3, 4, 1, 5.当找回6、2、3、4、1、5时,损失花数量分别为24、28、16、12、6、0 。 24 + 28 + 16 + 12 + 6 = 86.
题目链接
典型的贪心算法,一定是要先送破坏力大的牛回去,怎么来计算谁的破坏力大呢,可以用d/t,算出相对破坏力,按这个从大到小的顺序排序即可,注意要能够用long long
AC代码
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
#define Mod 1000000007
#define eps 1e-6
#define ll long long
#define INF 0x3f3f3f3f
#define MEM(x,y) memset(x,y,sizeof(x))
#define Maxn 100000+100
using namespace std;
int n;
struct node
{
int t;//时间
int d;//破坏力
};
node a[Maxn];
bool cmp(node x,node y)
{
// 破坏力/时间,易得谁的破坏力大,先送破坏力大的回家
double t1=(x.d*1.0)/(x.t*1.0);
double t2=(y.d*1.0)/(y.t*1.0);
return t1>t2;
}
int main()
{
cin>>n;
// 题目强调了结果在64位整数范围内,注意用ll
ll sum=0;//全部破坏的花朵数量
ll ans=0;//最终答案
for(int i=0; i<n; i++)
{
cin>>a[i].t>>a[i].d;
sum+=a[i].d;
}
sort(a,a+n,cmp);//按破坏力从大到小排序
// 排序结果
// for(int i=0;i<n;i++)
// cout<<a[i].t<<" "<<a[i].d<<endl;
for(int i=0; i<n-1; i++)
{
sum-=a[i].d;//送哪个走,哪个破坏的花朵数量就不能计算在内,其他的都要乘上这头牛的时间再*2
ans+=sum*a[i].t*2;
}
cout<<ans<<endl;
return 0;
}