NC25043 [USACO 2007 Jan S]Protecting the Flowers

题目

题目描述

Farmer John went to cut some wood and left N(2N100,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 (1Ti2,000,000) away from its own barn. Furthermore, while waiting for transport, she destroys Di(1Di100) 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.

输入描述

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

输出描述

Line 1 : A single integer that is the minimum number of destroyed flowers

示例1

输入

6
3 1
2 5
2 3
3 2
4 1
1 6

输出

86

题解

知识点:贪心,数学,排序。

注意到,交换某两头牛运送顺序,不改变其他结果。只要使任意两头牛的排序产生的毁坏最小,那么总毁坏将会是最小的,可以证明这是一个偏序关系,因此可以利用相邻两头牛的排序,来得到排序公式。

p1,p2 为相邻两牛毁坏的花, p1,p2 为两牛逆序后毁坏的花,且 p1+p2p1+p2

设之前所有牛的运送时间和为 Σ

所以有

p1=2ΣD1,p2=2(Σ+T1)D2p1=2ΣD2,p2=2(Σ+T2)D1

显然有,p1p2p1p2 。为了使 p1+p2p1+p2 ,那么

2ΣD1+2(Σ+T1)D22ΣD2+2(Σ+T2)D12Σ(D1+D2)+2T1D22Σ(D1+D2)+2T2D1T1D2T2D1

因此按此排序,最后序列的毁坏最小。

时间复杂度 O(nlogn)

空间复杂度 O(n)

代码

#include <bits/stdc++.h>
using namespace std;
struct pk {
int t, d;
}p[100007];
int main() {
std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;
cin >> n;
for (int i = 0;i < n;i++) {
cin >> p[i].t >> p[i].d;
}
sort(p, p + n, [&](pk a, pk b) {return a.t * b.d < b.t *a.d;});
long long sum = 0, time = 0;
for (int i = 0;i < n;i++) {
sum += time * p[i].d;
time += 2 * p[i].t;
}
cout << sum << '\n';
return 0;
}
posted @   空白菌  阅读(50)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示