算法中的表格式对齐

算法中的表格式对齐

有没有办法将每一行封装在一些虚线中,并在右侧添加 2 列,使其看起来像下面的图片?并且我可以在每一行上写数学方程式或类似的东西?就像您如何使用常量方法计算算法的时间复杂度一样。

\documentclass[11pt]{article}
\usepackage[noend]{algorithmic}
\usepackage{algorithm}

\begin{document}
\begin{algorithm}[H]
\begin{algorithmic}[1]
\FOR{i = 1..n} 
    \IF {A[i] $>$ 0}
        \FOR{j = 1..i}
            \IF{A[j] mod 2 == 0}
                \FOR{k = 1..j}
                    \STATE s = s + i + j + k
                \ENDFOR
            \ENDIF
        \ENDFOR
    \ENDIF        
\ENDFOR        
\RETURN s
\end{algorithmic}
\caption{Algorithm1(A[0..n], n)}
\end{algorithm}
\end{document}

所以我想要类似这样的东西: 这

答案1

tabularx以下是使用“伪造”或“重新创建”包外观的示例algorithm。算法编号是自动输入的,引用也有效:

在此处输入图片描述

\documentclass[11pt]{article}
\usepackage[noend]{algorithmic}
\usepackage{algorithm}
\usepackage{tabularx}
\begin{document}

\begin{algorithm}[H]
\begin{algorithmic}[1]
\FOR{i = 1..n} 
    \IF {A[i] $>$ 0}
        \FOR{j = 1..i}
            \IF{A[j] mod 2 == 0}
                \FOR{k = 1..j}
                    \STATE s = s + i + j + k
                \ENDFOR
            \ENDIF
        \ENDFOR
    \ENDIF        
\ENDFOR        
\RETURN s
\end{algorithmic}
\caption{Algorithm1(A[0..n], n)}\label{example1}
\end{algorithm}

\noindent
  \begin{tabularx}{\textwidth}{@{}Xcc@{}}
    \hline
    \refstepcounter{algorithm}\textbf{Algorithm \thealgorithm}\label{example2} Algorithm1(A[0..n], n) & Cost & Frequency \\
    \hline \vspace{-10pt}
    \begin{algorithmic}[1]
\FOR{i = 1..n} 
    \IF {A[i] $>$ 0}
        \FOR{j = 1..i}
            \IF{A[j] mod 2 == 0}
                \FOR{k = 1..j}
                    \STATE s = s + i + j + k
                \ENDFOR
            \ENDIF
        \ENDFOR
    \ENDIF        
\ENDFOR        
\RETURN s
\end{algorithmic} & c1 & c2\\[-13pt]
\hline
  \end{tabularx}

\begin{algorithm}[H]
\begin{algorithmic}[1]
\FOR{i = 1..n} 
    \IF {A[i] $>$ 0}
        \FOR{j = 1..i}
            \IF{A[j] mod 2 == 0}
                \FOR{k = 1..j}
                    \STATE s = s + i + j + k
                \ENDFOR
            \ENDIF
        \ENDFOR
    \ENDIF        
\ENDFOR        
\RETURN s
\end{algorithmic}
\caption{Algorithm1(A[0..n], n)}\label{example3}
\end{algorithm}

Referencing the algorithms:
\ref{example1}
\ref{example2}
\ref{example3}
\end{document}

更新:

在此处输入图片描述

\documentclass[11pt]{article}
\usepackage[noend]{algorithmic}
\usepackage{algorithm}
\usepackage{tabularx}
\usepackage{arydshln}
\begin{document}

\noindent
  \begin{tabularx}{\textwidth}{>{\footnotesize}rXcc@{}}
    \hline
    \multicolumn{2}{@{}l}{\refstepcounter{algorithm}\textbf{Algorithm \thealgorithm}\label{example2} Algorithm1(A[0..n], n)} & Cost & Frequency \\
    \hline
     1: & \textbf{for} i = 1..n \textbf{do} & text & other text\\ \hdashline
     2: & \quad\textbf{if} A[i] $>$ 0 \textbf{then} & more text & another text\\ \hdashline
     3: & \quad\quad\textbf{for} j = 1..i \textbf{do} & text & again text\\
\hline
  \end{tabularx}

\end{document}

相关内容