如何使用 Tikz 将多个节点合并为一个大节点?

如何使用 Tikz 将多个节点合并为一个大节点?

我必须实现 Gomory-Hu 算法,它需要将多个节点重新合并到一个节点,就像它显示的那样这里

enter image description here

我的代码非常简单,因为我想要实现的示例非常简单并且只包含一个图形和一棵在每次迭代中扩展的树:

\begin{tikzpicture}[auto, node distance=3cm, every loop/.style={},
thick,main node/.style={circle,fill=green!50,draw,font=\sffamily\Large\bfseries},
path/.style={circle, inner sep=2pt,fill=red!50, draw,font=\sffamily\Large\bfseries}]
\tikzstyle{edge_style} = [draw=orange, line width=2, ultra thick]

\node[main node] (b) {a,b,c,d,e};
\node[main node] (a) [below left = 1cm of b] {a};
\node[main node] (c) [right = 1.5cm of b] {c};
\node[main node] (f) [below  = 2cm of b] {f};
\node[main node](e)  [right = 1.5cm of f] {e};
\node[main node](d)  [below right = 1cm of c] {d};
\end{tikzpicture}

如您所见,到目前为止,我只能为节点赋予 a、b、c、d 这样的名称,但我想要的是获取一个包含名称为 a、b、c、d 的节点。

答案1

如果您想要分组的所有节点都很接近,fit那么定义节点的库fit可以帮助您。

我不明白图形和代码之间的关系,但以下代码使用fit节点生成所需的图形。

\documentclass[border=2mm,tikz]{standalone}
\usetikzlibrary{positioning, fit, shapes.geometric}

\begin{document}
\begin{tikzpicture}[auto, every loop/.style={},
thick,
main node/.style={circle,fill=green!50,draw,font=\sffamily\Large\bfseries},
path/.style={circle, inner sep=2pt,fill=red!50, draw,font=\sffamily\Large\bfseries},
edge_style/.style={draw=orange, line width=2, ultra thick}]

\node[main node] (1) {1};
\node[main node, below= 1mm of 1] (2) {2};
\node[main node, below left= -1mm and 3mm of 1] (0) {0};
\node[main node, below right=-1mm and 3mm of 1] (4) {4};

\node[ellipse, draw=red, fit=(0) (1) (2) (4), inner sep=-1mm] (all) {};

\node[main node, red, fill=gray, above right=5mm and 2cm of all] (3) {3};
\node[main node, blue, fill=gray, below right=5mm and 2cm of all] (5) {5};

\draw (all) -- node [above] {4} (3);
\draw[dashed] (all) -- node[below] {2} (5) -- node[right] {6} (3);
\end{tikzpicture}
\end{document}

enter image description here

答案2

几乎与 Ignasi 的回答相同... :)。我假设节点 0、1、2 和 4 的位置并不重要,并且可以位于圆上,而周围的线不必是椭圆:

enter image description here

对于上图,我尝试编写尽可能简短的代码,其中只使用需要的样式:

\documentclass[border=3mm,tikz,preview]{standalone}

\usetikzlibrary{fit,positioning}
    \begin{document}
\begin{tikzpicture}[auto, thick,
 node distance = 7mm and 22mm,
MN/.style args = {#1/#2}{circle,
                         draw=#1,
                         fill=#2,
                         inner sep=0.5mm, outer sep=0mm,
                         font=\sffamily\Large\bfseries},
    MN/.default = black/white
                    ]

\foreach \i[count=\ix from 0] in {0,1,2,4}
    \node (n\i) [MN,node distance=0mm] at ({90*\ix}:4.2mm) {\i};
\node (a)   [MN=red/none,fit=(n0) (n2)] {};
\node (n3)  [MN=red/gray!50,
             above right=of a] {3};
\node (n5)  [MN=blue/gray!50,
             below right=of a] {5};
\draw (a) -- node {4} (n3);
\draw[dashed]   (n3) -- node {6} (n5)
                (n5) -- node {3} (a);
\end{tikzpicture}
    \end{document}

相关内容