Crossing River

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不大于3的时候,让用时最少的人作为中间的运船者所用时间最短;n大于3的时候,先从小到大排序,对于a1 ... an (ai!=aj) ,有两种方法运输,第一种,a1作为中间来回传输者,time=a2+...+ an +(n-1)*a1 ;第二种:将a1,a2分居两侧,an,a(n-1)一起过去,a2将船运回来,a1将a2送回去,a1将船运回来,重复上述步骤到剩余3个或2个。所以只需要比较a1+a1+an+a(n-1) 与 a1 + a2+an+a2 的大小来决定采取哪种策略渡河。

#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
//#include <unordered_map>
#include <map>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <utility>
#include <cstring>
//#include <multimap>
//#include <multiset>
#define ll long long
#define inf 0x3f3f3f3f
const long long INF = 0x3f3f3f3f3f3f3f3f ;
using namespace std;
const int mxn = 1000+10 ;
#define TLE std::ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ls now<<1,l,mid
#define rs now<<1|1,mid+1,r
#define lc now<<1
#define rc now<<1|1
#define upsum(now) rt[now].sum =rt[now<<1].sum + rt[now<<1|1].sum ;
#define upmx(now) rt[now].mx = max(rt[now<<1].mx , rt[now<<1|1].mx) ;
#define pb push_back
int n,m,k,t,dp[mxn][mxn],a[mxn],sum[mxn];
string str ;
int prime[mxn], isprime[mxn];
int main()
{
    TLE;
    cin>>t;
    while(t--)
    {
        cin>>n;
        for(int i=1; i<=n; i++)
            cin>>a[i] ;
        sort(a+1,a+1+n);
        int tim = 0 ;
        for(int i=n;; i-=2)
        {
            if(i==1) {tim+=a[1];break;}
            else if(i==3){tim+=a[1]+a[2]+a[3];break;}
            else if(i==2){tim+=a[2];break;}
            else
                tim+= min(a[1]+a[i]+a[i-1]+a[1], 2*a[2]+a[1]+a[i] ) ;
        }
        cout<<tim<<endl;
    }
    return 0 ;
}
发布了94 篇原创文章 · 获赞 29 · 访问量 8552

猜你喜欢

转载自blog.csdn.net/m0_43382549/article/details/104217807