Test instructions: Tell you n points, M edge, ask you what is the minimum value of the difference between the longest edge and the shortest edge in their spanning tree, if the graph is not connected to output-1.
Idea: Kruskal algorithm, enumeration starting edge, for each Kruskal algorithm, the last edge is necessarily the longest side, directly return the difference with the starting edge.
#include <cstdio>#include<iostream>#include<algorithm>#include<cstring>#include<string>#include<map>#include<Set>#include<queue>#include<vector>#include<cmath>using namespacestd;Const intinf=0x3f3f3f3f;Const intmaxn= the;Const intmaxm=5500;intn,m;structedge{intU,v,w;} EDGE[MAXM];intPAR[MAXN];BOOLCMP (Edge A,edge b) {returna.w<B.W;}voidinit () { for(intI=0; i<=n;i++) Par[i]=i;}intFindintx) { returnx==par[x]?x:par[x]=find (Par[x]);}intKruskal (intflag) {init (); intCnt=0; for(inti=flag;i<m;i++) { intu=find (EDGE[I].U); intv=find (EDGE[I].V); if(u!=v) {Par[v]=u; CNT++; } if(cnt==n-1) returnedge[i].w-EDGE[FLAG].W; } return-1;//Non-Unicom}intMain () {//freopen ("In.txt", "R", stdin); while(SCANF ("%d%d", &n,&m) && (n| |m)) { for(intI=0; i<m;i++) scanf ("%d%d%d",&edge[i].u,&edge[i].v,&EDGE[I].W); Sort (Edge,edge+m,cmp); intAns=kruskal (0); for(intI=1; i<m-n+2; i++) { inttmp=Kruskal (i); if(tmp!=-1) ans=min (ans,tmp); } printf ("%d\n", ans); } return 0;}
View Code
POJ 3522 Slim Span