poj 1700 Crossing Rive(贪心)

来源:互联网 发布:ps软件错误16 编辑:程序博客网 时间:2024/06/05 07:39
Crossing River
Time Limit: 1000MS
Memory Limit: 10000KTotal Submissions: 9776
Accepted: 3693

Description

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

141 2 5 10

Sample Output

17

Source

POJ Monthly--2004.07.18

解题思路:
  首先按照过河时间从小到大排序,当n>3时候,就是考虑用最小时间先把用时最长的两个人送过河,
且手电筒仍然留在未过河的这边,剩下的再依次求解。

把当前用时最长的两个人送过河可以考虑两种方案:
方案一:
  1 号和 2 号先过河,然后 1 号回来,n 号和 n-1 号过河,然后 2 号再回来
用时:2*a[2]+a[1]+a[n];
方案二:
  1 号和 n 号先过河,然后 1 号再回来,1 号和 n-1 号再过河,之后 1 号再回来
用时:a[n]+a[n-1]+2*a[1];

  所以每次把用时最长的两个人送过河用时应该取上述两种方案中的最小值。至于为什么要先考虑
把用时最长的两个人送个和用的是贪心的思想,因为只有两个用时最长的两个人一块过河才能保证
用时次长的人不会占用过河时间,将时间降到最低(我是这样考虑的,不知道对不对。。)

代码如下:



package 贪心;import java.util.Arrays;import java.util.Scanner;public class poj_Crossing_River {//poj1700public static void main(String[] args) {Scanner sc=new Scanner(System.in);int T =sc.nextInt();while(T-->0){int N =sc.nextInt();int a[]=new int [N];for(int i=0; i<N; i++)a[i]=sc.nextInt();    int sum=0; Arrays.sort(a);if(N<=2){System.out.println(a[N-1]);continue;}if(N==3){System.out.println(a[0]+a[1]+a[2]);continue;} sum =a[1]; for(int i=N-1; i>=3; i-=2){sum +=Math.min(a[0]+a[i]+a[0]+a[i-1], a[0]+a[1]+a[i]+a[1]);}if(N%2==1)sum +=a[2]+a[0];//奇数的时候,别忘了,错了半天!!   System.out.println(sum);}}}