N 朵花,每朵有枯萎速度 Dᵢ 和保護時間 Tᵢ。每次只能保護一朵花,保護時其他花持續枯萎。求保護順序使總損失最小。
若順序為 π,總損失 = 2 × Σ(D_{πᵢ} × Σ_{j
相鄰交換法:比較 i、j 相鄰時的順序影響
i 應在 j 前 ⇔ Dᵢ/Tᵢ > Dⱼ/Tⱼ
#include <cstdio>
#include <algorithm>
using namespace std;
struct Flower { long long d, t; } a[100010];
bool cmp(const Flower& x, const Flower& y) {
return x.d * y.t > y.d * x.t; // 避免浮點,交叉相乘比較
}
int main() {
int n;
while (scanf("%d", &n) == 1) {
for (int i = 0; i < n; i++)
scanf("%lld%lld", &a[i].d, &a[i].t);
sort(a, a + n, cmp);
long long ans = 0, time_sum = 0;
for (int i = 0; i < n; i++) {
ans += 2 * time_sum * a[i].d;
time_sum += a[i].t;
}
printf("%lld\n", ans);
}
return 0;
}