微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用于在导线上拟合子间隔的贪婪算法

如何解决用于在导线上拟合子间隔的贪婪算法

我目前正在研究一些贪婪算法。

我有这个问题的描述:

There is a long electrical wire of length ℓ
centimetres between two poles where birds like to sit. After a long day at work you like to watch 
the birds on the wire from your balcony. 
Some time ago you noticed that they don’t like to sit closer than d centimetres from each other. In 
addition,they cannot sit closer than 6 centimetres to any of the poles,since there are spikes
attached to the pole to keep it clean from faeces that would otherwise damage and weaken it. 
You start wondering how many more birds can possibly sit on the wire

Given numbers ℓ and d,how many additional birds can sit on the wire given the positions of the  
birds already on the wire? For the purposes of this problem we assume that the birds have zero width.

The first line contains three space separated integers: the length of the wire ℓ,distance d and 
number of birds n already sitting on the wire. 
The next n lines contain the positions of the birds in any order. 
All number are integers,1≤ℓ,d≤1000000000 and 0≤n≤20000. 
(If you have objections to the physical plausibility of fitting that many birds on a line hanging 
between two poles,you may either imagine that the height of the line is 0 cm above ground level,or 
that the birds are ants instead.) 
You can assume that the birds already sitting on the wire are at least 6 cm from the poles and at least d centimetres apart from each other.

我必须输出一个Integer,它是电线上可以容纳的最大额外鸟类数量

示例输入和输出 进出 22 2 2 3 11 9 和 进出 47 5 0 8

尝试

我最初的想法是对电线上有多少可用空间进行一些计算。对于这里的第一个示例输入,数组看起来像这样:

enter image description here

(这里红色方块是电线上的位置,离极点太近,而蓝色方块已被占用)

现在,我只需要遍历这个数组,一旦我击中一个“免费”物品,然后在其中放一只新鸟,并把它的d-1个邻居标记为已居住(如果还没有)。

我现在将手动执行此想法,在该列表中,我将与i一起进行迭代,并将新占用的地方涂成黄色:

enter image description here

接下来,我们降落在i = 15,然后撞到另一个空位

enter image description here

但是,这给我的结果与测试用例不同,我一定做错了什么? 另外,我非常希望对一般方法学发表一些评论,有什么办法可以使我变得更聪明?

我反复进行,下次我碰到一个空位:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。