P3366 minimum spanning tree [template + Kruskal explanation]

The array size of this question is very important

Algorithm process:

  • Now all the edges are sorted according to the weight (from small to large).
  • Consider each edge in order (same as above), as long as the edge and the previously selected edge do not form a circle, keep the edge, otherwise discard the edge.

Concrete algorithm

  • After (n-1) edges are selected successfully, a minimum spanning tree is formed. If (n-1) edges cannot be selected, it means they are not connected.
  • When all points are connected, the execution ends.

Why n-1 edge?

The form of the above figure can be converted into the form of the following figure [there are n circles and (n-1) edges in the figure]


Is it very easy to understand?

Attach detailed code here

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int parent[10000110];
int n,m;
int i,j;
struct edge
int u,v,w; //Vertex of edge, weight
//Initialize and query set
void UFset()
parent[i] = -1;
//lookup i Root of 
int find(int i)
int temp; //Lookup location for(temp=i;parent[temp]>=0;temp=parent[temp]); //Compression path while(temp!=i){ int t=parent[i]; parent[i]=temp; i=t; } return temp; } //Combine two elements a,b void merge(int a,int b){ int r1=find(a); int r2=find(b); int tmp=parent[r1] + parent[r2]; //The sum of two set nodes if(parent[r1]>parent[r2])//Rank ordering optimization { parent[r1]=r2; parent[r2]=tmp; }else{ parent[r2]=r1; parent[r1]=tmp; } } void kruskal() { int sumWeight=0; int num=0; int u,v; UFset(); for(int i=0;i<m;i++) { u=edges[i].u; v=edges[i].v; //One node, one node if(find(u)!=find(v)) { //u and v Not in a set (able to form a circle, i.e. in the same set) sumWeight+=edges[i].w;//Calculate the sum of weights num++;//Calculation times, add as needed, can not add merge(u,v); //Add these two sides to a set. } } printf("%d \n",sumWeight); } //sort int cmp(const void * a, const void * b){ edge * e1 = (edge *)a; edge * e2 = (edge *)b; return e1->w - e2->w; } int main() { scanf("%d %d", &n,&m); for(i=0; i<m; i++) { scanf("%d %d %d", &edges[i].u,&edges[i].v,&edges[i].w); } qsort(edges,m,sizeof(edge),cmp);//Sort by weight kruskal();// return 0; }

Time complexity: O(NlogN) [N is the number of nodes]

 Happy ending!

Tags: C++

Posted on Thu, 13 Feb 2020 13:49:33 -0500 by justintoo1