给定一个元素排列 {1, 2, 3, ..., N}
,需要使用交换操作将其排序。交换元素x和y的操作的成本为min(x,y)。
需要找出对排列进行排序的最小成本。我考虑贪心地从N
到1
遍历并使用交换操作将每个元素放在其位置上,但这不是一个好主意。
给定一个元素排列 {1, 2, 3, ..., N}
,需要使用交换操作将其排序。交换元素x和y的操作的成本为min(x,y)。
需要找出对排列进行排序的最小成本。我考虑贪心地从N
到1
遍历并使用交换操作将每个元素放在其位置上,但这不是一个好主意。
编辑2:相信这将捕获所有情况。
while ( unsorted ) {
while ( 1 != index(1) )
swap (1 , index (1) )
if (index(2) == value@(2))
swap (2, value@(2) )
else
swap (1 , highest value out of place)
}
Find element 2
If it is not at correct place already
Find element at position 2
If swapping that with 2 puts both to right place
Swap them
Cost = Cost + min(2, other swapped element)
repeat
Find element 1
If element 1 is at position 1
Find first element that is in wrong place
If no element found
set sorted true
else
Swap found element with element 1
Cost = Cost + 1
else
Find element that should go to the position where 1 is
Swap found element with element 1
Cost = Cost + 1
until sorted is true
嗯,一个有趣的问题。我脑海里浮现出来的一个快速算法是使用元素作为索引。我们首先找到值为1的元素的索引,并将其与该数字的元素交换。最终,这将导致1出现在第一个位置,这意味着您必须将1与尚未处于正确位置的某个元素交换并继续。这个算法在排列(2、3、...、N、1)的情况下的下限为N-1,但确切的成本会有所变化,最高可达2 * N-2。
好的,考虑到上述算法和示例,我认为最优秀的方法是通过不断地用任何元素交换1直到它首先到达第一位,然后如果它还没有在正确的位置上,就将2与第二位交换,然后继续用尚未处于正确位置的任何内容交换1,直到排序完成。
set sorted=false
while (!sorted) {
if (element 1 is in place) {
if (element 2 is in place) {
find any element NOT in place
if (no element found) sorted=true
else {
swap 1 with element found
cost++
}
} else {
swap 2 with element at second place
cost+=2
}
} else {
find element with number equals to position of element 1
swap 1 with element found
cost++
}
}
如果你想通过重复交换来排序范围,你可以反复进行“推进和循环”操作:推进已经排序好的范围(其中 a[i] == i
),然后将a[i]
与a[a[i]]
交换,直到完成循环为止。重复此过程,直到达到末尾。这最多需要 N - 1 次交换,并基本上执行排列的循环分解。
使用桶排序,桶大小为1。
成本为零,因为没有交换发生。
现在通过桶数组进行一次遍历,并将每个值交换回原始数组中的相应位置。
这是N次交换。
N的总和为N(N+1)/2,给您一个确切的固定成本。
另一种解释是,您只需从桶数组中存储回原始数组即可。那就没有交换,因此成本为零,这是一个合理的最小值。
[4,3,2,1]
- 最优解是交换 (1,4) 和 (2,3),代价为 3。 - dfb