Title: Slim Span UVA 1395
Test instructions: Give a pair of non-right graph, survival into the smallest of the tree slender (maximum weight minus the minimum weight), if the tree can not be generated, the output-1;
Idea: All the edges by the weights have small to large sort, and then enumerate each edge, with this edge began to use the Kruskal algorithm to generate the tree, the generation process to find the maximum value, the maximum value minus the current enumeration of the edge of the weight is the slender degree, and then dynamic maintenance of the minimum size can be.
#include <iostream>#include<algorithm>#include<queue>#include<stack>#include<cstdio>#include<string>#include<cstring>#include<sstream>#include<cmath>#defineINF 0x3f3f3f3f#defineMoD 1000000007;#defineFRE () freopen ("In.txt", "R", stdin)using namespacestd;Const intMAXN =5005;structedge{intSt,en; intW;} E[MAXN];intPRE[MAXN];intn,m;BOOLCMD (Edge &a,edge &b) { returnA.W <B.W;}int_find (intx) { returnx = = Pre[x]? X:PRE[X] =_find (pre[x]);}intMain () {//FRE (); while(SCANF ("%d%d", &n,&m) && n+m) { for(inti =0; I < m; i++) {scanf ("%d%d%d",&e[i].st,&e[i].en,&E[I].W); } sort (E, E+m, cmd); intAns =INF; for(inti =0; I < m; i++)//enumerate each edge from small to large, then subtract the weight of the edge with the maximum value obtained { for(inti =1; I <= N; i++) Pre[i] =i; intCNT = N,mmax =-1; for(intj = i; J < M; J + +) { intx = _find (e[j].st), y =_find (E[j].en); if(X! =y) {pre[y]=x; CNT--; Mmax= Max (Mmax, E[J].W);//finding the largest weight in the smallest spanning tree } } if(CNT = =1)//because it is a tree, so there are n-1 edge, when it is a tree, the dynamic maintenance of the minimum valueans = min (ans, mmax-E[I].W); } if(ans = =INF) printf ("-1\n"); Elseprintf ("%d\n", ans); } return 0;}
View Code
UVA1395 Slim Span (Kruskal)