贪心算法总结理解(19.3.16~19.3.22)

一.贪心概念

贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,他所做出的是在某种意义上的局部最优解。
上周我对一部分贪心算法的题目进行了整理总结,这周也多做了一些题目,想着在这里整理一下思路,那话不多说,直接上题来分析

二.贪心例题

(1)过河问题
ep:
描述
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.
输入
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. There won’t be more than 1000 people and nobody takes more than 100 seconds to cross.
输出
For each test case, print a line containing the total number of seconds required for all the N people to cross the river.
(该题大致意思是)一组N个人只想用一艘船过河,最多只能载两个人。因此,必须进行某种安排,以便来回划船,以便所有人都能通过。每个人都有不同的划船速度;一对划船的速度由另一对划船速度较慢的决定(例如一个人划船速度为4,另一个人为5,若两人同时乘船,那么船的速度为速度较慢的人的划船速度为4)。你的工作是确定一个策略,尽量减少这些人的沟通时间。
分析
此题很有意思,它和普通的贪心问题不太一样,此题的解答有两种方案,而究竟哪种所用时间最少,需要我们进行进一步的判断。
第一种方案,让速度最快的人来回送人,也就是说,假如一共四个人,划船速度分别为1 2 3 4,那这个想法的思路就是让速度为1的人来回接送,这样能使得返回得时间最短。
第二种方案,只考虑速度最快的两人和速度最慢的两个人,还是1 2 3 4,先让1 2 过去,然后1划船回来,再让3 4过去,2划船回来.
我们想出这两种方案之后,就要判断哪个所用时间最短,可能光看思路还是有点不太清楚,上代码看一眼:

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int a[1000];
int n;
int cmp(int a,int b)
{
   
       return a<b;
}
int min(int a,int b)
{
   
       return a<b?a:b;
}
 int judge(int n)
{
   
   if(n==1)
  {
   
      return a[1];       //如果只有一位,速度为一个人的速度
  }
 if(n==2)
 {
   
      return a[2];     //如果有两位,速度为相对速度较慢的人的划船速度
 }
 if(n==3)
 {
   
      return a[1]+a[2]+a[3]
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值