我想在 latex 中编写一个算法。有多种编写方法,但我想按照下面给出的方式编写。我试过了,但我无法做任何类似于图中给出的事情。
看看我的代码:
\documentclass{article}
\usepackage[utf8]{inputenc}
\begin{document}
Algorithm \\
Input :
Output : \\
1. $T \leftarrow $ an set of size $S$ \\
2. \textbf{if} $x = 0$\\
3. \hspace{1cm} \textbf{return}
\end{document}
问题 : 我面临的一些问题是背景颜色、行号、间距等
答案1
根据 @CaptainNabla 的精彩回答:
\documentclass{article}
\usepackage{geometry}
\usepackage{enumitem}
\usepackage[framemethod=tikz]{mdframed}
\usepackage{lipsum}
\begin{document}
\begin{mdframed}[hidealllines=true,backgroundcolor=gray!20]
\parindent=0pt
\parskip=2pt % <-- gives more spaces between paragraphs
\underline{\textsc{ALLSUBSETSUMS}$^\#(S,u)$:}
\medskip % for additional vertical space
\textsf{INPUT:} A set $S$ of $n$ positive integers and an upper bound integer $u$.
\textsf{OUTPUT:} The set of all subset sums with cardinality information of $S$ up to $u$.
\begin{enumerate}[nosep]
\item \textbf{if} $S=\{x\}$
\item \hspace{1cm} \textbf{return} $\{(0,0),(x,1)\}$
\item $T \leftarrow$ an arbitrary subset of $S$ of size $[n/2]$
\item \textbf{return} \textsc{ALLSUBSETSUMS}$^{\#}(T,u)\bigoplus_u$\textsc{ALLSUBSETSUMS}$^{\#}(S\setminus T,u)$
\end{enumerate}
\end{mdframed}
\lipsum[1]
\end{document}
给出:
答案2
背景颜色可以按说明进行调整这里。然后就只需要摆弄一些字体了:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[framemethod=tikz]{mdframed}
\begin{document}
\begin{mdframed}[hidealllines=true,backgroundcolor=gray!20]
\noindent
\underline{\textsc{AllSubsetSums}\(^\#(S,u)\):}\\
\noindent\textsf{INPUT:} A set \(S\) of \(n\) positive integers and an upper bound integer \(u\).\\
\textsf{OUTPUT:} The set of all subset sums with cardinality information of \(S\) up to \(u\).
\begin{enumerate}
\item \textbf{if} \(S=\{x\}\)
\item \hspace{1cm} \textbf{return} \(\{(0,0),(x,1)\}\)
\item \(T \leftarrow\) an arbitrary subset of \(S\) of size \([n/2]\)
\item \textbf{return} \textsc{AllSubsetSums}\(^\#(T,u)\oplus_u\)\textsc{AllSubsetSums}\(^\#(S\setminus T,u)\)
\end{enumerate}
\end{mdframed}
\end{document}
它并不完美,仍然需要大量调整,特别是如果你有很多不同的算法。那么最好重新定义段落命令...