Crossing River POJ - 1700
A group of N people wishes to go across a river with only one boat, which can at most carry two persons. Therefore some sort of shuttle arrangement must be arranged in order to row the boat back and forth so that all people may cross. Each person has a different rowing speed; the speed of a couple is determined by the speed of the slower one. Your job is to determine a strategy that minimizes the time for these people to get across.
Input
The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. The first line of each case contains N, and the second line contains N integers giving the time for each people to cross the river. Each case is preceded by a blank line. There won't be more than 1000 people and nobody takes more than 100 seconds to cross.
Output
For each test case, print a line containing the total number of seconds required for all the N people to cross the river.
Sample Input
1
4
1 2 5 10
Sample Output
17
题目大意
有n个人要过河 每次只能两个人 并且每个人有自己的速度,划船过河的速度取决于速度最慢的人 求所有人过河最快要多少秒
分析
猜+证
分 slove1 2两种情况
一个是慢带快 一个是 每次相对最快的 过河 回来一个最快的 在走最慢的一组 回来最快的 ...
然后在两种情况下选择最小的
最后的出口 就是剩余 1 2 3 人的情况 记得break退出while

代码
package POJ;
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.min;
public class _1700_快速过河 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int n = sc.nextInt();
int[] speed = new int[n];
for (int j = 0; j < n; j++) {
speed[j] = sc.nextInt();
}
//排序
Arrays.sort(speed);
f(n, speed);
}
}
private static void f(int n, int[] speed) {
int left = n;//最慢的
int ans = 0;
while (left > 0) {
if (left == 1) {
ans += speed[0];
break;
} else if (left == 2) {
ans += speed[1];//两人就是 最慢的人
break;
} else if (left == 3) {
ans += speed[0] + speed[1] + speed[2];
break;
} else {
//第一种 最快的带最慢的 1,2-1; 1,3-1 ;1,4
int s1 = 2 * speed[0] + speed[left - 1] + speed[left - 2];
//第二种 顾眼前 相对最快都过去 回来一个 最快的
//12 出发 返回1 最后两个出发 返回2
//1 ,2-1;3,4——2 ; 1 2
int s2 = speed[1] + speed[0] + speed[left - 1] + speed[1];
ans += min(s1, s2);
left -= 2;//left代表剩余人数
}
}
System.out.println(ans);
}
}
本文地址:https://dxoca.cn/Algorithm/238.html 百度已收录
版权说明:若无注明,本文皆为“Dxoca's blog (寒光博客)”原创,转载请保留文章出处。