贪 心 算 法 +思维题

1.题目引入:

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.

 2.样例输出:

Sample Input

1
4
1 2 5 10

Sample Output

17

 题目大意:一条船一次能带两个人,并且只有一条船,也就是说到达河对岸后这条船还需要返回,现在给出每个人渡河一趟所花费的时间,求将所有人都运送到达河对岸所花费的时间。显然如果人在1-3个时,可以直接确定他们花费的总时间,当人数超过3个时,则需要判断:我们想到的最简单的方法就是每次都让速度最快的人随行,然后再返回。这不失为一个好的办法,但当这些人的速度都特别慢时,显然这个方法并不能满足最小的时间,这个时候就需要我们引入另一种方法来解决这个问题,即:我们先让最快的两个人先乘船渡河,然后让最快的那个人乘船返回,然后让未上船的人中最慢的两个人上船,然后让河对岸中最快的那个人乘船返回(即所有人中次快的那个人)。以此类推我们发现当人数为奇数时最后会剩下 3 个人即最快的三个人,当人数为偶数时最后会剩下两个人即最快的两个人,这两种方法取最小值就是我们所要求的结果。

至此这道题的思路已经出现,那么如何实现它呢(点个赞我们继续往下看),显然我们发现这是一个贪心算法,因此需要我们将他们渡船时间从小到大进行排序,然后按照我们的思路进行模拟就行,这里给大家写出了具体的实现过程和解释,代码如下:

3.代码如下: 

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e5+10;
int a[maxn];
int main()
{
	int t,n;
	cin>>t;
	while(t--)
	{
		cin>>n;
		for(int i=1;i<=n;i++)
		{
			cin>>a[i];
		}
		sort(a+1,a+n+1);
		int ans=0;
		if(n==1)  ans=a[1];   // 当 n=1 n=2 时等于它本身 
		else if(n==2) ans=a[2];
	    // 当 n=3 时也可以直接确定它的值 即最快两人先离开然后让离开的人最快的返回带第三个人离开 
		else if(n==3)    
		{
			ans+=a[1]+a[2]+a[3];
		}
		// 当人数超过四个时 
		else
		{
			int sum1,sum2;
			for(int i=n;i>=4;i-=2) //一次运两个人 (i>=4 会剩下最后一次或两次运送 这时就需要分两种情况) 
			{
				sum1=a[i]+a[i-1]+a[1]*2;  //最快的人依次运送两个人 
				// 先让最快的跟次快的过河,然后让最快的回来,再让最慢的跟次慢的过河,再让次快的回来
				sum2=a[2]+a[1]+a[i]+a[2];  
				ans+=min(sum1,sum2);   // 取两者最小的即可 
			}
			if(n&1)  // 如果 n 为奇数的话最后会只剩下 3 个人 
			{
				ans+=a[3]+a[1]+a[2];
			}
			else    // 如果  n 为偶数的话最后会剩下 2 个人 
			{
				ans+=a[2];
			}
		}
		cout<<ans<<"\n";
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风遥~

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

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值