Uva1395slim Span (enumeration minimum spanning tree)

Source: Internet
Author: User

Test instructions: In the minimum spanning tree, the largest edge minus the minimum edge minimum value.

It's easy to see the =_=.

Sort each edge from small to large and then enumerate the smallest spanning tree from smallest to largest, updating the minimum when forming a spanning tree

1#include <iostream>2#include <cstdio>3#include <cstring>4#include <algorithm>5 using namespacestd;6 Const intINF =0x3f3f3f3f;7 Const intMax = the;8 Const intN = the;9 intFather[n];Ten structEdge One { A     intx, Y, Dist; - }; - Edge Edge[max]; the intcmp (Edge t1, Edge T2) - { -     returnT1.dist <t2.dist; - } + intFind_father (intx) - { +     if(x = =Father[x]) A         returnx; at     returnFATHER[X] =Find_father (father[x]); - } - intMain () - { -     intN, M; -      while(SCANF ("%d%d", &n, &m)! =EOF) in     { -         if(M = =0&& n = =0) to              Break; +          for(inti =0; I < m; i++) -         { thescanf"%d%d%d", &edge[i].x, &AMP;EDGE[I].Y, &edge[i].dist); *         } $Sort (edge, Edge +m, CMP);Panax Notoginseng         intMinn =INF; -          for(inti =0; I < m; i++) the         { +              for(intj =0; J <= N; J + +) AFATHER[J] =J; the             intCNT =0; +              for(intj = i; J < M; J + +)//enumerate each spanning tree in turn -             { $                 intFX =Find_father (edge[j].x); $                 intFY =Find_father (EDGE[J].Y); -                 if(FX! =fy) -                 { theFATHER[FX] =fy; -cnt++;Wuyi                     if(cnt = = N-1)//Once the spanning tree is formed, j is the maximum edge, I is the least weight, and the subtraction is updated the                     { -Minn = MIN (minn, edge[j].dist-edge[i].dist); Wu                          Break; -                     } About                 } $             } -         } -         if(Minn = =INF) -printf"-1\n"); A         Else +printf"%d\n", Minn); the     } -     return 0; $}
View Code

Uva1395slim Span (enumeration minimum spanning tree)

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.