贪心算法学习总结

这一周我看了了很多贪心算法的题。简单总结了个人理解贪心算法的核心思想。

局部最优 :不从整体上进行考虑,对于一个问题总是做出当前情况的最优解。

贪心算法的优点在于做决策只要考虑当前情况,条件较为简单,问题的复杂度大大降低。但其缺点就是局部的最优解不一定是全局的最优解。

简单的例子就是背包问题:两种情况

(1)0-1背包问题,物品不可分割。这时候使用贪心算法,很有可能导致浪费大量背包空间,局部的最优解往往不等于全局最优解。这类问题需要使用动态规划求解。

(2)背包问题,物品可以分割。这类问题就可以使用贪心算法,由局部最优解得到全局最优解。

例题:

Least Cost Bracket Sequence

https://blog.csdn.net/fouzhe/article/details/56022900

This is yet another problem on regular bracket sequences.

A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.

For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

Input
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi(1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.

Output
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.

Print -1, if there is no answer. If the answer is not unique, print any of them. 

题意:

是给一个序列,序列里面会有左括号、问号、右括号。对于一个‘?’而言,可以将其替换为一个‘(’,也可以替换成一个‘)’,但是都有相应的代价。

问:如何替换使得代价最小。前提是替换之后的序列中,括号是匹配的。如果不能替换为一个括号匹配的序列则输出-1。

题解:

先假设所有的‘?’全部替换成右括号,然后按常规的办法去检测这个序列是否括号匹配。

所谓的常规的办法就是遍历这个序列,维护一个计数器cnt,当遇到左括号时计数器+1,遇到右括号时计数器-1

如果中途遇到cnt小于0的情况,则说明这个序列不是括号匹配的,但是在我们这里,右括号可能是‘?’变来的,所以当遇到cnt小于0时,则去看前面有没有‘?’变过来的右括号,如果没有,那就说明无论如何这个序列无法被替换为括号匹配的序列;如果有的话,则选取一个“最好”的由‘?’变过来的右括号,将其改为左括号,这样的话cnt又可以加2了。这里所谓的“最好”,就是贪心的过程。

总结

贪心算法我在之前几周就已经学过,当时觉得还是比较简单的,但如今看了新的博客,发现还是有很多不懂的,有时不是很懂贪心算法的思想时,也搜过好些代码,慢慢总结规律,自己总算琢磨出贪心算法的思想以及它的思路,对它的限制和不足也有所了解。学习贪心算法的过程,几乎都是在琢磨他们的代码是如何得出的,是如何想到这一方法的,他们的思想确实让我受益匪浅。

本周由于准备线代考试,说实话看的内容并不多,加上博客的题目难度都挺大,往往看懂一个题需要一个小时,这周抽空看也就看了五六道,所以这周的内容并不多。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值