我在算法和算法环境中编写伪代码,但编号和排版都完全混乱了。
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage[noend]{algpseudocode}
\usepackage{amsmath,amssymb}
\begin{document}
\begin{algorithm}
\vspace*{2mm}
\caption{Backtracking for TSP} \label{alg:backtracking}
\emph{TSP\_BruteForce1(R,S)}
\begin{algorithmic}[1]
\If {$S$ empty}
\State $minCost$ \gets length tour
\Else{}
\State $minCost \gets \infty$
\ForEach {city $i$ in $S$}
\State Remove $i$ from $S$ and append $i$ to $R$
\State $minCost$ \gets $min(minCost, TSP\_BruteForce1(R,S))$
\State Reinsert $i$ in $S$ and remove $i$ from $R$
\EndFor
\EndIf
\Return {$minCost$}
\end{algorithmic}
\end{algorithm}
\end{document}
我尝试过在各处添加和删除花括号,但没有什么作用。
答案1
你在这里混合了不兼容的软件包 - algorithmic
(来自algorithms
捆)和algpseudocode
(来自algorithmicx
)。删除前者并为变量和函数调用进行一些新的定义。当然,您可以根据自己的喜好更改这些。
\documentclass{article}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\usepackage{amsmath}
\newcommand{\var}{\texttt}
\newcommand{\func}{\textsl}
\newcommand{\algorithmicforeach}{\textbf{for each}}
\algdef{S}[FOR]{ForEach}[1]{\algorithmicforeach\ #1\ \algorithmicdo}
\begin{document}
\begin{algorithm}
\caption{Backtracking for TSP}
\func{TSP\_BruteForce1}($\var{R}, \var{S}$)
\begin{algorithmic}[1]
\If {$S$ empty}
\State $\var{minCost} \gets \text{length tour}$
\Else
\State $\var{minCost} \gets \infty$
\ForEach {city $i$ in $S$}
\State Remove $i$ from $S$ and append $i$ to $R$
\State $\var{minCost} \gets \min(\var{minCost}, \func{TSP\_BruteForce1}(R, S))$
\State Reinsert $i$ in $S$ and remove $i$ from $R$
\EndFor
\EndIf
\State \Return \var{minCost}
\end{algorithmic}
\end{algorithm}
\end{document}