【每日一题】Protecting the Flowers
Protecting the Flowers
https://ac.nowcoder.com/acm/problem/25043
题目描述:
有一群牛在花园里面,农夫需要一个个地把牛运送到牛舍,已知农夫把牛运到牛舍需要地时间(分钟)time以及牛每分钟破坏的花的数目destroy,给出一个数n,n头牛,下面有n行,每行两个数字分别使time,destroy.问如何搬运牛才能使花被破坏的数目最少。
题目求解:
我们可以看牛群中A,B两头牛,显然任意改变A,B两头牛的位置都对前面的搬运没有影响;
1.假设A牛放在B牛的前面,对于后面的影响有:sum * A.destroy+(sum+2 * A.time) * B.destroy
2.假设B牛在A牛的前面,对于后面的影响有:sum * B.destroy+(sum+ 2 * B.time) * A.destroy
3.不妨假设A放在前面比较好,那么sum * A.destroy+(sum+ 2 * A.time) * B.destroy<sum * B.destroy+(sum+2 * B.time) * A.destroy. 也就是 A.time * B.destroy<A.destroy * B.time.
代码如下:
#include <bits/stdc++.h> #include <algorithm> #include<cstdio> using namespace std; #define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0) typedef long long ll; const ll MOD = 1e5 + 7; const ll maxn =1e5+7; struct node{ int t,d; bool operator<(const node&b) const{ return t*b.d<b.t*d; }//结构体内嵌比较函数 }a[maxn]; int main(){ js; int n; cin>>n; for(int i=0;i<n;i++) cin>>a[i].t>>a[i].d; sort(a,a+n); ll time=0,ans=0; for(int i=0;i<n;i++){ ans+=time*a[i].d; time+=2*a[i].t; } cout<<ans<<endl; }