The smallest spanning tree is the Benquan smallest tree that a graph can generate.
Method (Kruskal algorithm): all Benquan are sorted from small to large, then one side checks, if join this side formed a loop, then do not join the tree, otherwise join. As for how to judge the circuit, use and check set maintenance can.
Code:
1#include <cstdio>2#include <cstdlib>3#include <cmath>4#include <cstring>5#include <iostream>6#include <algorithm>7#include <string>8#include <vector>9#include <queue>Ten#include <stack> One using namespacestd; A Const intMAXN =1e5; - Const intINF =1<< -; -typedefstruct the { - intU, V, W;//connecting U,v Two-point weighted w edge - } Power; - +Power edge[maxn+5]; -Power res[maxn+5]; + intfather[maxn+5]; A intN, M;//number of points and edges at - BOOLCMP (Power A, power B) - { - returnA.W <B.W; - } - in intFind (intx) - { to if(Father[x] = = x)returnx; + Else returnFATHER[X] =Find (father[x]); - } the * intMain () $ {Panax Notoginsengscanf"%d%d", &n, &m); - for(inti =1; I <= n;i++) father[i] =i; the for(inti =1; I <= m;i++) + { Ascanf" %d%d%d", &edge[i].u, &EDGE[I].V, &EDGE[I].W); the } +Sort (Edge +1, Edge +1+m, CMP); - intAns =0, cnt =0; $ for(inti =1; I <= m;i++) $ { - intU = edge[i].u, V = edge[i].v, w =EDGE[I].W; - if(Find (u)! =Find (v)) the { -Father[find (u)] =Find (v);WuyiAns + =W; thecnt++; -res[cnt].u = u; RES[CNT].V = v; RES[CNT].W =W; Wu } - } Aboutprintf"%d\n", ans); $ for(inti =1; I <= cnt;i++) - { -printf"%d%d%d\n", Res[i].u, RES[I].V, RES[I].W); - } A return 0; +}
Minimum spanning tree (Kruskal algorithm)