UVA1395 Slim Span (Kruskal)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.