Basic idea: First mark several vertices from the non-graph, then select the least-weighted edge from the marker vertex, and the other vertex of the edge is not marked until all points have been marked.
Algorithm implementation: Using the array vis to denote the point of the case, the array low represents the minimum weight associated with the point case.
1 intPrimintN)2 {3 inti,j;4 intMin,pos;5 intans=0;6 7vis[0]=1; pos=0;8 9 for(i=0; i<n; i++)Ten if(I!=pos) low[i]=Dis[pos][i]; One A for(i=0; i<n; i++)//n-1 Secondary Cycle - { -Min =MaxInt; the for(j=0; j<n; J + +) - if(vis[j]==0&& min>Low[j]) - { -min=Low[j]; +pos=J; - } + Aans+=min; atvis[pos]=1; - - for(j=0; j<n; J + +) - if(vis[j]==0&& Low[j]>dis[pos][j])//Update minimum weights -low[j]=Dis[pos][j]; - } in returnans; -}
Basic idea: For all edges in an untagged graph, each time you select the lowest weight from the currently selected edge and do not form the edge of the ring with the selected edge, until all points are marked, determining whether the selected edge constitutes a ring can be implemented by using a and check.
Algorithm implementation: Using the array pre to record and check the root node of the focus point situation
typedefstructedge{intA; intb; intvalue;}; Edge Map[max];intPre[max];voidInit ()//and check the initialization of the set{ for(intI=0; i<=max; i++) Pre[i]=i;}intFindintX//find the root node of x and compress the path{ intR=x; while(PRE[R]!=R)//R=pre[r] means R is the root nodeR=Pre[r]; //Path Compression intJ,i=x; while(i!=R) {J=Pre[i]; Pre[i]=R; I=J; } returnR;}BOOLJoinintXintY//Judging whether it is a ring{ introot1=find (x); intRoot2=find (y); if(ROOT1==ROOT2)return false; PRE[ROOT1]=root2;//Merging return true;}intKruskal () {intI=0, A, B; intans=0; intnum=1; while(num<N) {a=map[i].a; b=map[i].b; if(Join (b)) {ans+=Map[i].value; Num++; } I++; } returnans;}
Minimum spanning tree of graph theory