[POJ ]1700 Crossing Rive 快速过河 贪心策略
Crossing River POJ - 1700 A group of N people wishes to g... 10
2019/08

# [POJ ]1700 Crossing Rive 快速过河 贪心策略

## 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

## 分析 ## 代码

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;
break;
} else if (left == 2) {
ans +=  speed;//两人就是 最慢的人
break;
} else if (left == 3) {
ans += speed + speed + speed;
break;
} else {
//第一种 最快的带最慢的 1，2-1； 1，3-1 ；1，4
int s1 = 2 * speed + speed[left - 1] + speed[left - 2];
//第二种 顾眼前 相对最快都过去 回来一个 最快的
//12 出发 返回1 最后两个出发 返回2
//1 ，2-1；3，4——2 ； 1 2
int s2 = speed + speed + speed[left - 1] + speed;
ans += min(s1, s2);
left -= 2;//left代表剩余人数
}
}
System.out.println(ans);
}
}

百度已收录

Last modification：August 11th, 2019 at 11:32 am 