An example of whether the MST is unique.
Poj1679-the Unique MST
Test instructions: For the given graph, the MST (minimum spanning tree) is unique, the unique output path is long, otherwise the output is not unique!
The puzzle: Whether the MST is unique depends on whether the weights are the same on both sides (where one edge is in the MST for the first time and the other outside the MST).
If such an edge exists, you will need to delete that edge from the MST one at a time, and then seek the MST again, and if this is the same as the first MST, there does not exist a unique MST
Otherwise, there must be no more than one MST.
1 //kruskal-determine if MST is unique2 //time:0ms memory:868k3#include <iostream>4#include <cstring>5#include <cstdio>6#include <algorithm>7 using namespacestd;8 9 #defineMAX 101Ten One structEdge { A intu, v; - intW; - BOOLUsed;//First used the BOOLDel//Kruskal Whether this edge is not considered -FriendBOOL operator< (Edge e1, Edge E2) {returnE1.W <E2.W;} -}e[max*MAX]; - + intN, M; - BOOLFirst//whether to ask for MST for the first time + intFa[max]; A intDel[max*max], Len;//edges to be removed successively at intMinroad;//First MST results - - intFind (intx) - { - returnFA[X] <0? X:FA[X] =Find (fa[x]); - } in - voidUnion (intR1,intR2) to { +R1 =Find (R1); -r2 =Find (R2); the intnum = Fa[r1] +FA[R2]; * if(Fa[r1] <FA[R2]) $ {Panax NotoginsengFA[R2] =R1; -FA[R1] =num; the } + Else { AFA[R1] =R2; theFA[R2] =num; + } - } $ $ BOOLKruskal () - { -memset (FA,-1,sizeof(FA)); the intnum =0; - intMind =0;Wuyi for(inti =0; I < m; i++) the { - if(E[i].del)Continue; Wu if(Find (e[i].u) = = Find (E[I].V))Continue; - Union (e[i].u, E[I].V); About if(first) { $Minroad + =E[I].W; -e[i].used =true; - } -Mind + =E[I].W; A if(Mind > Minroad)return true; + if(++num = = N-1) Break; the } - $ return false; the } the the intMain () the { - intT; inscanf"%d", &T); the while(t--) the { Aboutscanf"%d%d", &n, &m); theMemset (E,0,sizeof(e)); the for(inti =0; I < m; i++) thescanf"%d%d%d", &e[i].u, &E[I].V, &E[I].W); + -Len =0; theSort (E, E +m);Bayi for(inti =0; I < m; i++) the if(E[I].W = = E[i +1].W) the { - if(del[len-1] = i) del[len++] =i; -del[len++] = i +1; the } the theMinroad =0; theFirst =true; - Kruskal (); theFirst =false; the the BOOLUnique =true;94 for(inti =0; i < Len; i++) the { the if(!e[del[i]].used)Continue;//used to delete theE[del[i]].del =true;//Delete98 if(!Kruskal ()) About { -printf"Not unique!\n");101Unique =false; Break;102 }103E[del[i]].del =false;//Recovery104 } the 106 if(unique)107printf"%d\n", minroad);108 }109 the 111 the return 0;113}
The-kruskal solution of ACM/ICPC's distinguishing MST uniqueness (POJ1679)