# Crossing river 贪心

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

1.                   河

sum_time1 = t1+t2+t3+t4 = 2*a + c + d
2.                    河

sum_time1 =  t1+t2+t3+t4 = a + 2*b + d

Source

#include<iostream>
#include<algorithm>
using namespace std;

int a[1004];
int main()
{
int t;
cin >> t;
while(t--)
{
int n, ans = 0;
cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i];
sort(a+1, a+n+1);
while(n > 3)
{
if(a[1] + a[n-1] < 2 * a[2])
ans += (2 * a[1] + a[n-1] + a[n]);
else
ans += (a[1] + 2 * a[2] + a[n]);
n -= 2;
}
if(n == 3)
ans += a[1] + a[2] + a[3];
else if(n == 2)
ans += a[2];
else
ans += a[1];
cout << ans << endl;
}
}//有需排序的样例，打乱输入样例测试结果。 

        sort(a,a+n);
dp[0]=a[0];
dp[1]=a[1];
for(int i=2;i<n;i++)
dp[i]=min(dp[i-1]+a[0]+a[i],dp[i-2]+a[0]+a[i]+a[1]*2);
cout<<dp[n-1]<<endl;

---------------------

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

会悟

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
09-26 77

04-27 137
07-11 412
11-01 206
08-08 420
07-16 301