题目:
花园里有n头牛,每头牛有ti和di。代表将它迁回家要花2*ti时间,而呆在花园里每单位时间消灭di朵花儿。问你按什么顺序牵牛使被消灭的花儿总数最小。输出最小总数。
做法:
相邻两头牛的顺序不影响除它们之外的所有牛的贡献,这是典型的贪心。
若牛A排在前面比牛B排在前面优,可以列出如下式子:
移项化简:
按这个式子排序。得到最优牵牛回家的方案。然后统计一下被牛消灭的花的数量即可。
代码:
#include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
#define debug(a) cout << #a ": " << a << endl
using namespace std;
typedef long long ll;
const int N = 1e5 + 7;
struct node{
ll t, d;
bool operator < (const node& rh)const{
return t*rh.d < d*rh.t;
}
}a[N];
int main(void){
IOS;
int n; cin >> n;
for (int i = 1; i <= n; ++i){
cin >> a[i].t >> a[i].d;
}
sort(a+1, a+n+1);
ll wait = 0;
ll ans = 0;
for (int i = 1; i <= n; ++i){
ans += wait*a[i].d;
wait += 2*a[i].t;
}
cout << ans << endl;
return 0;
}
京公网安备 11010502036488号