Kruskal's algorithm (Kruskal)

definition

Kruskal's algorithm is an algorithm used to find the minimum spanning tree.

ready

Tree: if a loop does not exist no connected graph in which the graph is called a tree.

MST: the tree all vertices of a sub FIG no connected graph G G if it is contained in one, the subgraph of G called the spanning tree.

Minimal spanning tree is connected subgraphs of the connectivity graph. Here, the term refers to the minimum: an edge if any increase in the tree, a loop will occur; if one side removed, so will not communicate with FIG.

Minimum Spanning Tree: for communication spanning tree undirected graph, the sum of the weight of each value is called the right side of the spanning tree, a minimum weight spanning tree called the minimum spanning tree.

There are three criteria constitute a Spanning Tree:

① must only use the network side to construct a minimum spanning tree.

② must be used and only the n-1 connected to the network edges of the n vertices

③ can not be used to produce side circuit.

achieve

  ① the original weights in each edge from small to large order.

  ② small to large in order to determine each edge.

       If the current side does not form a loop with the current minimum spanning tree, then the current edge join the current minimum spanning tree.

       On the contrary, the edge is abandoned, continues to determine the next edge.

       Until the selected (top points -1) of the edge, at which point the minimum spanning tree is a spanning tree. (Typically utilize disjoint-set determines whether or not to form a loop)

 

 

   ① sorting 

 

 

   ② small to large to determine each edge.

  

Code

#include<bits/stdc++.h>
using namespace std;
struct node
{
 int u,v,w;
 node(){}
 node(int a,int b,int c) {u=a;v=b;w=c;}
 bool operator <(const node &n) const
 {return w<n.w;}
};
int f[1000];
vector<node> edge;
int find(int p)
{return f[p]==-1?p:f[p]=find(f[p]);}
int main()
{
  fill(f,f+1000,-1);
  int u,v,w,i,x,y,sum=0,cnt=0,n;
  scanf("%d",&n);
  for(i=0;i<n;i++)
  {
    scanf("%d%d%d",&u,&v,&w);
    edge.push_back(node(u,v,w));
  }
  sort(edge.begin(),edge.end());
  for(i=0;i<edge.size();i++)
  {
      x=find(edge[i].u);
      y=find(edge[i].v);
      if(x!=y)
      {
         f[y]=x;
         sum+=edge[i].w;
         printf("%d %d %d\n",edge[i].u,edge[i].v,edge[i].w);
         if(++cnt==n-1) break;
      }
    }
  printf("最小生成树权值为%d",sum);
  system("pause");
  return 0;
}

 

Guess you like

Origin www.cnblogs.com/VividBinGo/p/11576064.html