专栏名称: LaTeX工作室
欢迎光临分享与学习LaTeX的王国
目录
相关文章推荐
51好读  ›  专栏  ›  LaTeX工作室

algorithm2e 算法中间行号第一行和最后一行不完全对齐的问题修复

LaTeX工作室  · 公众号  ·  · 2025-03-18 21:07

正文

点击👇 LaTeX工作室 关注公众号
精致美好科研生活从 LaTeX 开始!


问题选自: https://ask.latexstudio.net/ask/question/17696.html

使用 algorithm2e 宏包时,算法中间行号第一行和最后一行不完全对齐的问题。即使在宏包文档的示例中也存在这个问题,即使改变字体样式,问题仍然存在。

问题复现

示例代码一:

\begin{algorithm}

\small
\KwIn{数据图$G=(V_G, E_G)$, 整数参数$K$, 以及查询顶点$v_q$ }
\KwOut{对应的包含$v_q$的$K$-truss社区集合}
visited= $\varnothing$$l = 0$ \label{code:truss-search:init} 

\For{$v_q$的每一个邻居$u$}
{
 \If{边$(v_q,u)$的{\rm truss}不小于$k$且并未访问过}
 {
  visited = visited$\cup \{(v_q, u)\}$\;
  $l ++$\;
  $C_l=\varnothing, Q=\varnothing$ \;
  $Q$.push$(v_q, u)$\;
  \While{$Q \neq \varnothing$}
  {
   $(x,y) = Q.$pop()\;
   $C_l.$push$((x,y))$\;
   \For{$z\in N(x)\cap N(y)$}
   {
    \If{$(x,z)$和$(y,z)$的{\rm truss}值均不小于$K$}
    {
     \If{$(x,z)$未访问过}
     {
      $Q.$push$((x,z))$\;
      visited = visited $\cup \{(x,z)\}$
     }
     \If{$(y,z)$未访问过}
     {
      $Q$.push$((y,z))$\;
      visited = visited $\cup \{(y,z)\}$
     }
    }
   }
  }
 }
}
Return \{$C_1$$\cdots$$C_l$\}
 
\caption{$K$-truss社区搜索在线查询算法}
 \label{alg:truss:search:online}
\end{algorithm}

不对齐的效果:

示例代码二:

\documentclass{article}
\usepackage[linesnumbered,ruled,noend,vlined]{algorithm2e}
\begin{document}
\begin{algorithm}
        visited= 12345, $l = 0$
        \For{$v_q$each neighbour$u$}
        {
        $C_l=12345, Q=12345$ \;
        $Q$.push$(v_q, u)$\;
            \While{$Q P W Y Z$}
            {
                $(x,y) = Q.$pop()\;
                $C_l.$push$((x,y))$\;
                \For{$z\in N(x)\cap N(y)$}
                {
                    pass
                }
            }
        }
        \KwRet{$\{C_1$,...,$C_l\}$}
\end{algorithm}
\end{document}

不对齐效果:

解决方案

实际上是中间的行号比前两行和最后一行更靠近右侧一点。这应该是 algorithm2e 的 bug。

在导言区重定义 \algocf@Vline \algocf@Vsline 即可。

解决代码如下:

\documentclass{ctexart}
\usepackage{amsmath,amssymb}
\usepackage[linesnumbered,lined,ruled,noend]{algorithm2e}
\SetArgSty{textrm}
\SetAlgorithmName{算法}{算法}{算法目录}

\makeatletter
\@ifpackagelater{algorithm2e}{2017/07/19}{}{% current version 2017/07/18
%%%%%%%%% block with a vertical line end by a little horizontal line
\renewcommand{\algocf@Vline}[1]{%     no vskip in between boxes but a strut to separate them, 
  \strut\par\nointerlineskip% then interblock space stay the same whatever is inside it
  \algocf@push{\skiprule}
%        move to the right before the vertical rule
  \hbox{\kern-.4pt\vrule%   %%     \vtop{\algocf@push{\skiptext}%move the right after the rule
      \vtop{\algocf@addskiptotal #1}\Hlne}}\vskip\skiphlne% inside the block
  \algocf@pop{\skiprule






请到「今天看啥」查看全文