Prim && Kruskal

Source: Internet
Author: User

Portal: Comforting cows

1#include <iostream>2#include <cstdio>3#include <algorithm>4#include <cstdlib>5 6 using namespacestd;7 8 structnode{9     intx,y,w;Ten };  One   ANode s[100010];//side - intSum//Record Minimum Time - intf[10010];//indicates that each vertex is on a different connected component. (i.e. the Father of the parent) the inttalk[10010];//record the conversation time for each ranch -  - voidInit ()//Initialize - { +     inti; -      for(i=0;i<10010; i++) +f[i]=i; A } at  - intCMP (node A,node b)//sort, small to large - { -     returna.w<B.W; - } -  in voidKruscal (intNintL//kruscal Entrance - { to     intQ;  +Sort (s,s+l,cmp); -     intnum=1, J;//record the number of edges the     intk=0;//Subscript of the loop edge *      while(num<N) $     {Panax Notoginseng         if(F[s[k].x]!=f[s[k].y])//determine if the edge is a loop -         { thenum++; +sum+=S[K].W; Aq=F[S[K].Y]; the              for(j=1; j<=n;j++)//cycle each and q equal vertices of the father. +             { -                 if(f[j]==q) f[j]=f[s[k].x]; $             } $         } -k++;//Loop each edge -     } the } - intMain ()Wuyi { the      -     intn,p,i; Wu      while(~SCANF ("%d%d",&n,&p)) -     { About init (); $sum=0; -         intmin=99999; -          for(i=1; i<=n;i++)//find the smallest vertex and start at this point -         { Ascanf"%d",&talk[i]); +             if(Min>talk[i]) min=Talk[i]; the         } -          for(i=0; i<p;i++)//constructs a connected graph that can generate the smallest tree.  $         { thescanf"%d%d%d",&s[i].x,&s[i].y,&S[I].W); thes[i].w=talk[s[i].x]+talk[s[i].y]+2*S[I].W; the         } the kruscal (n,p); -printf"%d\n", sum+min); in         //for (i=1;i<=n;i++) the vertex of the minimum spanning tree becomes a connected graph, that is, f[i] are equal the         //cout << f[i]<<endl; the     } About}
Kruskal Solutions

Prim && 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: 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.