最小生成树-Kruskal算法
比较成熟的算法,百度百科有,不赘述
Kruskal算法适用于边稀疏的情形,而Prim算法适用于边稠密的情形
主要是各种代码收集,最主要的还是c++的
3.1 伪代码
3.2 C
3.3 matlab
3.4 pascal
3.5 c++
3.6 java代码实现
3.7 Mathematica实现(如下)
(*Kruskal算法,点从1开始,时间不最优,但空间最小*) Clear[kruskal] kruskal[dian_, tuer_] := Module[ {dianf = {}, son = {}, biannum = Length[tuer], result = {}, s1, s2, f1, f2, bflag = False, tu}, son = Table[1, {i, 1, dian}]; dianf = Table[i, {i, 1, dian}]; tu = Sort[tuer, #1[[3]] < #2[[3]] &]; (*Print[tu];*) Do[ s1 = tu[[i, 1]]; s2 = tu[[i, 2]];(*取边,点*); f1 = dianf[[s1]]; f2 = dianf[[s2]]; While[f1 != s1, s1 = f1; f1 = dianf[[s1]]]; While[f2 != s2, s2 = f2; f2 = dianf[[s2]]];(*取父节点*) If[ s1 < s2, dianf[[s2]] = s1; son[[s1]] += son[[s2]]; AppendTo[result, tu[[i]]], If[s1 > s2, dianf[[s1]] = s2; son[[s2]] += son[[s1]]; AppendTo[result, tu[[i]]]] ]; If[son[[1]] == dian, bflag = True; Break]; , {i, 1, biannum}]; If[bflag, Return[result], Print["图不完整"]] ]
(*Kruskal算法,点从1开始,时间最小*) Clear[getfa, kruskal2, dianf] dianf = {};(*dianji需要实现定义*) getfa[s_] := Module[ {}, If[dianf[[s]] == s, Return [s], dianf[[s]] = getfa[dianf[[s]]]; Return [dianf[[s]]]]]; kruskal2[dian_, tuer_] := Module[ {son = {}, biannum = Length[tuer], result = {}, s1, s2, f1, f2, bflag = False, tu}, son = Table[1, {i, 1, dian}]; dianf = Table[i, {i, 1, dian}]; tu = Sort[tuer, #1[[3]] < #2[[3]] &]; (*Print[tu];*) Do[ s1 = tu[[i, 1]]; s2 = tu[[i, 2]];(*取边,点*); f1 = getfa[s1]; f2 = getfa[s2];(*取父节点*) (*Print[s1," ",f1," ",s2," ",f2];*) If[ f1 < f2, dianf[[f2]] = f1; dianf[[s2]] = f1; son[[f1]] += son[[f2]]; AppendTo[result, tu[[i]]], If[ f1 > f2, dianf[[f1]] = f2; dianf[[s1]] = f2; son[[f2]] += son[[f1]]; AppendTo[result, tu[[i]]]] ]; If[son[[1]] == dian, bflag = True; Break]; , {i, 1, biannum}]; If[bflag, Return[result], Print["图不完整"]] ]
示例:
tuer = {{1, 2, 1}, {1, 9, 2}, {1, 8, 1}, {2, 9, 1}, {2, 3, 1}, {9, 3, 3}, {3, 4, 1}, {9, 4, 4}, {4, 5, 5}, {5, 9, 4}, {5, 6, 2}, {6, 9, 2}, {6, 7, 3}, {7, 9, 5}, {7, 8, 5}, {8, 9, 4}} (*example 1*) In[139]:= kruskal[9, tuer] Out[139]= {{3, 4, 1}, {2, 3, 1}, {2, 9, 1}, {1, 8, 1}, {1, 2, 1}, {6, 9, 2}, {5, 6, 2}, {6, 7, 3}} (*example 2*) In[136]:= kruskal2[9, tuer] Out[136]= {{3, 4, 1}, {2, 3, 1}, {2, 9, 1}, {1, 8, 1}, {1, 2, 1}, {6, 9, 2}, {5, 6, 2}, {6, 7, 3}}