使用algorithm2e环境插入算法伪代码

之前的算法伪代码环境是algorithmicx和algpseudocode, 今天介绍algorithm2e环境。个人感觉algorithm2e更适合CS领域。

代码如下:

\documentclass{article}
\usepackage[linesnumbered,algoruled,boxed,lined]{algorithm2e}%环境
\begin{document}
\begin{minipage}{0.8\textwidth}%设置显示宽度
\begin{algorithm}[H]
\KwIn{Point set $P$}%输入,不需要\renewcommand
\KwOut{Subset $\tilde{P}$}%输出
\caption{Some algorithm}
\label{alg1}
Initialization\;%直接写,不用\State
\For{$i\leftarrow 2$ \KwTo $l$}{
a for loop\;
}
\end{algorithm}
\end{minipage}
\end{document} 

使用beamer做slides时,如果用algorithmicx和algpseudocode,动态演示的时候每进行一步,caption那里Algorithm编号会不断加1,Algorithm 1, Algorithm 2, ...

为了避免这个问题,我们可以使用algorithm2e,只需加一条命令

\resetcounteronoverlays{algocf}

下面是一个示例:

\documentclass{beamer}
\usepackage[linesnumbered,algoruled,boxed,lined]{algorithm2e}%环境
\resetcounteronoverlays{algocf}%加上这条命令阻止算法编号累加
\begin{document}
\begin{frame}{test}
\begin{center}
\begin{minipage}{0.8\textwidth}%可以控制宽度
\begin{algorithm}[H]
\small
\KwIn{Some input}%输入,不用像之前的那样加\renewcommand
\KwOut{Some output}%输出
\caption{Some algorithm}
\label{alg1}
initialization

\While{$i\le10$}
{
        read current\;
        \eIf{understand}
        {
            go to next section\;
            current section becomes this one\;
        }
        {
            go back to the beginning of current section\;
        }
}
\end{algorithm}
\end{minipage}
\end{center}
\pause

hahahaha
\end{frame}
\end{document} 

 

你可能感兴趣的:(Latex)