Mountain Climbing S

文章介绍了一个关于奶牛爬山问题的最优化算法,通过贪心方法确定奶牛上山和下山的顺序,以最少时间完成所有奶牛的旅程。
摘要由CSDN通过智能技术生成

题目描述

Farmer John has discovered that his cows produce higher quality milk when they are subject to strenuous exercise. He therefore decides to send his N cows (1 <= N <= 25,000) to climb up and then back down a nearby mountain!

Cow i takes U(i) time to climb up the mountain and then D(i) time to climb down the mountain. Being domesticated cows, each cow needs the help of a farmer for each leg of the climb, but due to the poor economy, there are only two farmers available, Farmer John and his cousin Farmer Don. FJ plans to guide cows for the upward climb, and FD will then guide the cows for the downward climb. Since every cow needs a guide, and there is only one farmer for each part of the voyage, at most one cow may be climbing upward at any point in time (assisted by FJ), and at most one cow may be climbing down at any point in time (assisted by FD). A group of cows may temporarily accumulate at the top of the mountain if they climb up and then need to wait for FD’s assistance before climbing down. Cows may climb down in a different order than they climbed up.

Please determine the least possible amount of time for all N cows to make the entire journey.

输入格式

第一行,一个整数 N。

第 22 到第 N+1 行,每行两个用空格隔开的整数 U(i) 和 D(i)。

(1 <= U(i),D(i) >= 50,000)。

输出格式

一行一个整数,表示所有 N 头牛完成旅程的最短时间。

题意翻译

农场主约翰发现他的奶牛剧烈运动后产奶的质量更高,所以他决定让 N 头(1≤N≤25,000) 奶牛去附近爬山再返回来。

第 ii 头奶牛用时 U(i) 爬上山,用时 D(i)下山。作为家畜,奶牛们每段路都要有农夫的帮助,可是由于经济疲软,农场里只有两个农夫 John 和 Don。John 计划引导奶牛爬山,Don 引导奶牛下山。虽然每个奶牛都需要向导,但每段旅途只有一名农夫。所有任何时刻只有一头奶牛爬山也只能有一头奶牛下山,奶牛爬上山后,可以暂时停留在山顶上等待 Don 的帮助。奶牛上山的顺序和下山的顺序不一定要相同。

请计算出所有 N 头牛完成旅程的最短时间。

输入样例

3
6 4
8 1
2 3

输出样例

17

解题思路

首先,虽然奶牛可以按照任意的顺序上下山,但是不难发现,下山的顺序是没必要调整的,如果同时有多只奶牛在山顶,她们按照任意顺序下山,都不影响答案,所以我们只需要考虑奶牛行动的顺序即可。

令当前最后一只奶牛上山的时间为 x,下山时间为 y,加上下一只上下山时间分别为 u 和 d 的奶牛,更新时间的方式为:

1.x 加上 u。
2.y 和 x 取较小值。
3.y 加上 d。
初始时 x 和 y 均为 0,最后的答案就是 y。 通过更新的方式可知,我们应该尽量避免 y 被 x 更新,由此可以贪心的安排顺序:

1.u<d 的奶牛应该比 u≥d 的奶牛先走。
2.在所有 u<d 的奶牛中, 小的奶牛应该先走,此时第一只奶牛上山的时间也最短。
3.在所有 du≥d 的奶牛中, 大的奶牛应该先走,此时最后一只奶牛下山的时间也最短。

解题代码

#include <bits/stdc++.h>
using namespace std;
using Pii = pair<int, int>;
const int kMaxN = 25001;
Pii a[kMaxN];
int n, x, y;
int C(Pii p) {                                           // 计算排序时的值
  return p.first < p.second ? p.first : 1e9 - p.second;  // 先比较两个值的大小关系,再比较对应值
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i].first >> a[i].second;
  }
  sort(a + 1, a + 1 + n, [](Pii i, Pii j) { return C(i) < C(j); });
  x = y = 0;  // 初始化时间
  for (auto p : a) {
    x += p.first;   // 累加上山时间
    y = max(x, y);  // 更新下山时间
    y += p.second;  // 累加下山时间
  }
  cout << y;
  return 0;
}
  • 22
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值