讓我們假設一個典型的演算法,如下所示:
\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}