“排序”的最快方法通过切换位来序列
给定有有限的随机序列,如何确定排序序列(即所有0和全部1)所需的最小位切换数量?
请注意,均质序列(例如0000000
和1111111
)被视为该定义分类。
另外,从技术上讲,这不是“排序”序列,因为元素被定位为原位,而不仅限于与其他元素交换,还有比“排序”更好地描述此活动的词?
Given a finite random sequence of bits, how can the minimum number of bit toggles necessary to result in a sorted sequence (i.e. any and all 0's are before any and all 1's) be determined?
Note, homogeneous sequences (e.g. 0000000
and 1111111
) are considered sorted by this definition.
Also, this is not technically "sorting" the sequence because elements are toggled in-place, not restricted to swapping with other elements, is there better word to describe this activity than "sorting"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
令z(n)为设置第一个n位全部0的成本
。令x(n)为“排序”第一n位的最低成本成本。
我们有:
z(0)= 0,x(0)= 0,
如果位点为0:z(i)= z(i-1),x(i)= min(z(i-1),x),x (i-1)+1)
如果位是1:z(i)= z(i-1)+1,x(i)= x(i-1),
答案为x(n)。
代码更容易:
Let Z(n) be the cost of setting the first n bits all 0.
Let X(n) be the cost of minimum cost of "sorting" the first n bits.
We have:
Z(0) = 0, X(0) = 0
if the ith bit is 0: Z(i) = Z(i-1), X(i) = min( Z(i-1), X(i-1)+1 )
if the ith bit is 1: Z(i) = Z(i-1)+1, X(i) = X(i-1)
The answer is X(n).
It's even easier in code:
一个规范的动态程序是在o(1)时间和空间中评估两个状态:保持位相同或切换的成本,同时将其分配为相关部分的最右边(也会产生相关的成本由于作业而引起的隐含切换)。
抱歉,以上内容适用于一般问题 - “排序”可以朝任何方向。 (要选择一个方向,请从下面的
最佳
变量分配中选择相关的方向。)Python代码:
输出:
One canonical dynamic program would be to evaluate in O(1) time and space two states for each bit: the cost of keeping the bit the same or toggling it, while assigning it as rightmost of the relevant section (also incurring the relevant cost for the implied toggles due to the assignment).
Sorry, the above applies to the general problem - where "sorted" could be in either direction. (To choose a direction, pick the relevant one from the
best
variable assignments below.)Python code:
Output: