Crossing river 贪心

本文详细解析了一道经典的过河问题算法,通过两种策略对比,介绍了如何最小化多人使用单船过河的时间。输入包括多组数据,每组数据包含人数及每个人的过河时间,输出则是各组数据的最短过河时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值