如何在算法中为连续的一行定义标签

如何在算法中为连续的一行定义标签

让我们假设一个典型的算法,如下所示:

\documentclass{article}
\usepackage{algorithm,algpseudocode}
\begin{document}
\begin{enumerate} 
  \item Some text\ldots\par
  \vspace{-\baselineskip}

  \begin{minipage}{\linewidth}
  \begin{algorithm}[H]
    \caption{Euclid’s algorithm}\label{euclid}
    \begin{algorithmic}[1]
      \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
        \State $r\gets a\bmod b$
        \While{$r\not=0$}\Comment{We have the answer if r is 0}
          \State $a\gets b$
          \State $b\gets r$
          \State $r\gets a\bmod b$
        \EndWhile\label{euclidendwhile}
        \State \textbf{return} $b$\Comment{The gcd is b}
      \EndProcedure
    \end{algorithmic}
  \end{algorithm}
  \end{minipage}

  Some more text\ldots
\end{enumerate}
\end{document}

我需要为算法的某些连续行插入标签,即类似下面的图像(垂直花括号覆盖第 n 行到第 m 行之间的行,然后a在其前面定位一个标签,例如):

在此处输入图片描述

请问我该怎么做呢?

答案1

这里有一个选项tikzmark

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations.pathreplacing}
\usepackage{algorithm,algpseudocode}


\newcommand{\tikzmark}[2][]{\tikz[remember picture,overlay]\node[inner xsep=0pt,inner ysep=1ex,#1](#2){};}

\begin{document}
\begin{enumerate} 
  \item Some text\ldots\par
  \vspace{-\baselineskip}

  \begin{minipage}{\linewidth}
  \begin{algorithm}[H]
    \caption{Euclid’s algorithm}\label{euclid}
    \begin{algorithmic}[1]
      \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
        \State $r\gets a\bmod b$
        \While{\tikzmark[xshift=-1.2cm]{A}$r\not=0$}\Comment{We have the answer if r is 0}
          \State $a\gets b$
          \State $b\gets r$
          \State $r\gets a\bmod b$
        \EndWhile\tikzmark{B}\label{euclidendwhile}
        \State \textbf{return} $b$\Comment{The gcd is b}
      \EndProcedure
    \end{algorithmic}
  \end{algorithm}
  \end{minipage}

\begin{tikzpicture}[remember picture,overlay]
\draw[red,thick,decorate,decoration={brace,amplitude=5pt,mirror}](A.north)--node[left=.3em]{a}(A|-B);
\end{tikzpicture}

  Some more text\ldots
\end{enumerate}
\end{document}

相关内容