POJ 1700 Crossing River

Crossing River

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 20000/10000K (Java/Other)
Total Submission(s) : 8   Accepted Submission(s) : 7
Problem 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
1 4 1 2 5 10
 
Sample Output
17
 
题目大意: 第一行输入T代表有T组数据,对于每组数据,然后第二行输入N,表示有N个人,第三行输入这N个人过河的时间,题目规定只有一只船,而且每一次最多只能载两个人,过河时间是两个人中慢的人的时间,求所有人过河的最短时间。
思路:现将时间从小到大排序,然后将N小于等于3的单独分出来,即:
				  if(N == 1) time += a[0];
				  if(N == 2) time += a[1];
				  if(N == 3) time += a[0] + a[1] + a[2];
而后对人数大于4的,将最快的前两个和最慢的两个人分为一组,而这四个人过河有两种方案:
方案一:由第一个带着第二个过河,而后第一个回来,然后倒数第一个和倒数第二个过河,然后让第二个2 划船过来,用时间为time = a[1] + a[0] + a[n - 1] + a[1];
方案二:由第一个人带着第二个,然后第一回来带着倒数第一个,然后回来带着倒数第二个过河,时间为time = a[1] + a[0] +  a[n - 1] + a[0] + a[n - 2];而后比较两次时间花费,采取时间少的累加。

#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
using namespace std;
bool cmp(int x, int y)
{
    return x < y;
}
int main()
{
    int a[1005];
    int n;
    int t;
    cin >> t;
    while (t--)
    {
        cin >> n;
        int i;
        for (i = 1; i <= n; i++)
            cin >> a[i];
        sort(a + 1, a + n + 1, cmp);
        int s = 0;
        while (n > 3)
        {
            s += min(a[2] + a[1] + a[n] + a[2], a[n - 1] + a[1] + a[n] + a[1]);
            n -= 2;
        }
        if (n == 3)
            s = s + a[1] + a[2] + a[3];
        if (n == 2)
            s = s + a[2];
        if (n == 1)
            s = s + a[1];
        cout << s << endl;
    }
    return 0;
}
 
 
原文地址:https://www.cnblogs.com/caiyishuai/p/8423847.html