algorithm2e 环境中的行延迟换行

algorithm2e 环境中的行延迟换行

我遇到了一个小问题,

Let $s$ be the highest-ranked student in $h$'s preference list which $h$ has not yet requested to be a resident\

我的算法中的换行有点太晚了。我认为边界应该与 fancyhdr 提供的“家庭作业 1”下的行相同。下面是我的 tex 文件的完整部分。有人能帮我让那行早点换行吗?如果我用换行符强制换行,那么它也会为算法环境提供错误的行号,因此快速修复不是我愿意接受的选项。

\begin{enumerate}
...
\item[\textbf{4.}] 
    Below is an algorithm to find a stable assignment of students to hospitals:

    \begin{algorithm}[H]
        \SetKwData{List}{list}
        \SetKwFunction{Remove}{Remove}
        \SetKwFunction{Insert}{Insert}
        \SetKwInOut{Input}{input}

        \Input{A set of hospitals $H$ where each $h \in H$ has a list of students $h.\List$ with a capacity equivalent to number of positions available \\ A set of students $S$}
        Initially $s$ is free for all $s \in S$ and $h.\List$ is empty for all $h \in H$. \\
        \While{there exists $h \in H$ such that $h.\List$ is not full}
        {
            Choose such a hospital $h$\\
            \While{$h.\List$ is not full}
            {
                Let $s$ be the highest-ranked student in $h$'s preference list which $h$ has not yet requested to be a resident\\
            }
        }
    \end{algorithm}
...
\end{enumerate}

答案1

根据algorithm2e代码,[H]-style 算法被设置为minipage宽度\hsize(英寸algorithm2e.sty):

%%% environment for {algorithm}[H]
\newenvironment{algocf@Here}{\noindent%
  \def\@captype{algocf}% if not defined, caption exit with an error
  \begin{minipage}{\hsize}%
}{%
  \end{minipage}%\par%
}%

将其更改为minipage宽度\linewidth即可解决问题。使用etoolbox修补\algocf@Here

在此处输入图片描述

\documentclass{article}
\usepackage{showframe,etoolbox}% http://ctan.org/pkg/{showframe,etoolbox}
\usepackage{algorithm2e}% http://ctan.org/pkg/algorithm2e

\makeatletter
\patchcmd{\algocf@Here}{\hsize}{\linewidth}{}{}
\makeatother
\begin{document}
\begin{enumerate}
\item[\textbf{4.}] 
    Below is an algorithm to find a stable assignment of students to hospitals:

    \begin{algorithm}[H]
        \SetKwData{List}{list}
        \SetKwFunction{Remove}{Remove}
        \SetKwFunction{Insert}{Insert}
        \SetKwInOut{Input}{input}

        \Input{A set of hospitals~$H$ where each $h \in H$ has a list of students $h.\List$ with a capacity equivalent to number of positions available \\
          A set of students~$S$}
        Initially~$s$ is free for all $s \in S$ and $h.\List$ is empty for all $h \in H$\;
        \While{there exists $h \in H$ such that $h.\List$ is not full}
        {
            Choose such a hospital~$h$\;
            \While{$h.\List$ is not full}
            {
                Let~$s$ be the highest-ranked student in~$h$'s preference list which~$h$ has not yet requested to be a resident
            }
        }
    \end{algorithm}
\end{enumerate}
\end{document}

\patchcmd{<cmd>}{<search>}{<replace>}{<success>}{<failure>}<search>用替换- 在本例中,用 替换<cmd>。给出了列表内行宽度的真实表示(在本例中为)。 有关这些长度差异的讨论,请参阅<replace>\hsize\linewidth\linewidthenumerate\textwidth\linewidth之间的区别\hsize

相关内容