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.
输入t组数据,每组数据第1行输入n,第2行输入n个数,表示每个人过河的时间。
Output
For each test case, print a line containing the total number of seconds required for all the N people to cross the river.
输出t行数据,每行1个数,表示每组过河最少时间。
Sample Input
1
4
1 2 5 10
Sample Output
17
开始题目没看明白,怎么过河,回来要不要时间都搞不清楚,后来找了英文题才明白,当然第二种策略也是没想到,题策略选择,两种过河策略:(过河时间 a < b < c < d)
1. 河
去 b,c -- t1 = d --> a,d
回 b,a,c <-- t2 = a -- d
去 b -- t3 = c --> a,c,d
回 b,a <-- t4 = a -- c,d
sum_time1 = t1+t2+t3+t4 = 2*a + c + d
2. 河
去 c,d -- t1 = b --> a,b
回 a,c,d <-- t2 = a -- b
去 a -- t3 = d --> c,d
回 a,b <- t4 = b -- c,d
sum_time1 = t1+t2+t3+t4 = a + 2*b + d
两种策略比较 a+c 与 2*b 哪个用时少选哪个,小于四人时直接出结果。
小经验:程序中有排序时,将sample input打乱顺序输入,另作case来测试来检验排序代码。
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;
---------------------
作者:Alex_McAvoy
来源:优快云
原文:https://blog.youkuaiyun.com/u011815404/article/details/80299153
版权声明:本文为博主原创文章,转载请附上博文链接!