版本比较
hanoisort
正文
增加 2 行删除 2 行
32 行未改动33343536373738394041424343444546474832 行未改动
- pop the top node $nd$ that satisfies $nd.pos>pos$ one by one. For each popped $nd$: - if $nd.diff=true$, i.e. the disk above the referred disk is located at the opposite pillar, we need to make them located at the same pillar. We either extend an operation to $nd.pos$, with $cost:=cost+2\times(\min\{optpos,nd.optpos\}-nd.pos)$; or reinitiate an operation, with $cost:=\max\{0,2\times(m-nd.pos)-1\}$. We pick the one with smaller cost. Finally, let $optpos:=nd.pos$. - if $nd.diff=false$, let $optpos:=\min\{optpos,nd.optpos\}$.
- after stack popping, if the top node has $nd.pos=pos$, we need to handle this node specially, since now we need to make the disks at $pos$ and $pos+1$ located at different pillars instead of the same pillar.
- if $nd.diff=true$, let $optpos:=\min\{optpos,nd.optpos\}$. - if $nd.diff=false$, let $cost:=cost+2\times(\min\{optpos,nd.optpos\}-nd.pos)$ or $cost:=\max\{0,2\times(m-nd.pos)-1\}$, and $optpos:=nd.pos$. - this node is also popped.
- if the top node has $nd.pos<pos$, or that the stack is empty, we still need to do something to make the disks at $pos$ and $pos+1$ located at different pillars. Let $cost:=\min\left\{cost+2\times(optpos-pos),\max\{0,2\times(i-pos)-1\}\right\}$ and $optpos:=pos$.
- after all above procedures, finally we need to push a node $\{pos-1,optpos,true\}$ onto the stack. However, if there is already a node with $nd.pos=pos-1$ at the top of the stack, then we need to do $nd.optpos:=\min\{nd.optpos,optpos\}$ and $nd.diff:=\neg nd.diff$.
The answer is $n+\sum_i cost$.