Topic Link http://poj.org/problem?id=3522
kruskal+ and check the collection, attention to special cases such as 1, 0, 0, 1,
1#include <cstdio>2#include <iostream>3#include <algorithm>4#include <climits>5 using namespacestd;6 #defineMAXN 50057 structedge{8 intU,v,cost;9 };Ten intCompConstedge& E1,Constedge&E2) { One returne1.cost<E2.cost; A } - Edge ES[MAXN]; - intv,e; the intPAR[MAXN],RANK[MAXN]; - voidinit () { - for(intI=1; i<=v;i++){ -par[i]=i; + } - } + intFindintx) { A if(par[x]==x)returnx; at returnpar[x]=find (par[x]); - } - voidUniteintXinty) { -x=find (x); -y=find (y); - if(x!=y) { inpar[x]=y; - } to } + BOOLSame (intXinty) { - returnFind (x) = =find (y); the } * intKruskal (intk) { $ init ();Panax Notoginseng intmin,max=-1; - intesum=0; the for(inti=k;i<e;i++){ + if(e-k<v-1) Break; AEdge e=Es[i]; the if(!Same (E.U,E.V)) { + Unite (E.U,E.V); -esum++; $Max=max<e.cost?E.cost:max; $ } - if(esum==v-1){ -min=Es[k].cost; the returnmax-min; - }Wuyi } the return-1; - } Wu intMain () - { About inti,flag=0; $ while(SCANF ("%d%d", &v,&e) = =2){ - if(v==0&&e==0) Break; - for(i=0; i<e;i++){ -scanf"%d%d%d",&es[i].u,&es[i].v,&es[i].cost); A } + if(e==0|| V> -|| e<v-1){ theprintf"-1\n");Continue;} -Sort (es,es+e,comp); $ intmin=int_max,x; the for(i=0; i<e-v+2; i++){ thex=Kruskal (i); the if(min>x&&x!=-1){ themin=x; - } in } the if(min!=Int_max) theprintf"%d\n", min); About Else theprintf"-1\n"); the } the return 0; +}
POJ 3522 Slim Span