写论文要写一个伪代码,伪代码中有一部分是一个递归函数,但是找了很久都没找到LaTex中Function怎么定义,各种依赖报错,折腾了很久终于可以用了,代码和效果如下:
\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage{algpseudocode}
\usepackage{amsmath}
\renewcommand{\algorithmicrequire}{\textbf{Input:}}
\renewcommand{\algorithmicensure}{\textbf{Output:}}
\begin{algorithm}
\caption{Mobility Tree Construction}
\label{alg:1}
\begin{algorithmic}[1] %每行显示行号
\Require One of the user's trajectory $traj$; The number of branches in the tree $nary$;
\Ensure The Mobility Tree $MT$ corresponding to the input trajectory
\Function {AddChild}{$MT, traj, idx, map, flags$}
\State $node\gets traj[idx]$
\State $map[idx]\gets$ The number of nodes in $MT$
\State Add $node$ to $MT$
\If {$idx > 0$ and $flag[idx] != 0$}
\State $flag[idx]\gets 0$
\State $i\gets nary$
\While{$i > 0$}
\State $child\gets$ \Call{AddChild}{$MT, traj, idx-i, map, flags$}
\State $edge\gets$ $child$ to $node$ // $src \rightarrow dst$
\State Add $edge$ to $MT$
\EndWhile
\EndIf
\State \Return{$node$}
\EndFunction
\State
\Function{ConstructTree}{$traj, nary$}
\State Initialize an empty tree $MT$ with no nodes and edges
\State Initialize an empty dictionary variable $map$
\State $len\gets$ The length of $traj$
\State Initialize the dictionary variable $flags$ of length $len$
\State \Call{AddChild}{$MT, traj, len-1, map, flags$}
\State \Return{$MT$}
\EndFunction
\end{algorithmic}
\end{algorithm}
但是导师说不太好看,建议我用Algorithm2e再改一改,再次Google并修改之,于是变成了以下版本:
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
\begin{algorithm}
\SetAlgoLined %显示end
\caption{Mobility Tree Construction}
\label{alg:1}
\KwIn{One of the user's trajectory $traj$; The number of branches in the tree $nary$;}
\KwOut{The Mobility Tree $MT$ corresponding to the input trajectory}
\SetKwProg{Fn}{Function}{:}{end}
\Fn{AddChild(MT, traj, idx, map, flags)}{
$node\gets traj_{idx}$\;
$map_{idx}\gets$ The number of nodes in $MT$\;
Add $node$ to $MT$\;
\If{$idx > 0$ and $flag_{idx} != 0$}{
$flag_{idx}\gets 0$\;
$i\gets nary$\;
\While{$i > 0$}{
$child\gets$ \textit{AddChild(MT, traj, idx-i, map, flags)}\;
$edge\gets$ $child$ to $node$ // $src \rightarrow dst$\;
Add $edge$ to $MT$\;
}
}
\Return{$node$}
}
\Fn{ConstructTree(traj, nary)}{
Initialize an empty tree $MT$ with no nodes and edges\;
Initialize an empty dictionary variable $map$\;
$len\gets$ The length of $traj$\;
Initialize the dictionary variable $flags$ of length $len$\;
\textit{AddChild(MT, traj, len-1, map, flags)}\;
\Return{$MT$}
}
\end{algorithm}