Poj 1861 Kruskal

Source: Internet
Author: User
# Include <iostream> # include <algorithm> # include <cstring> # include <queue> # include <cstdio> # include <map> using namespace STD; const int maxn = 1001; const int maxm = 15001; struct edge {int U, V, W;} edges [maxm]; int CMP (const void * a, const void * B) // sort by length {edge AA = * (const edge *) A; edge BB = * (const edge *) B; return AA. w-BB. w;} int parent [maxn]; int rank [maxn]; int n, m; int ans [maxn], AI; int num, maxedge; void Make_set () {for (INT I = 1; I <= N; I ++) {parent [I] = I; rank [I] = 1 ;}} int find (int x) {While (X! = Parent [x]) x = parent [X]; return X;} void Union (int x, int y) {x = find (X ); y = find (y); If (x = y) return; If (rank [x]> rank [y]) {parent [y] = X; rank [x] + = rank [y];} else {parent [x] = y; rank [y] + = rank [x] ;}} void Kruskal () {ai = 0; num = 0; int U, V; make_set (); For (INT I = 1; I <= m; I ++) {u = edges [I]. u; V = edges [I]. v; If (find (u )! = Find (V) // if no loop is formed {ans [ai] = I; AI ++; If (edges [I]. w> maxedge) maxedge = edges [I]. w; num ++; Union (u, v); // merged} If (Num> = n-1) Break ;}} int main () {While (CIN> N> m) {for (INT I = 1; I <= m; I ++) {CIN> edges [I]. u> edges [I]. v> edges [I]. w;} qsort (edges + 1, m, sizeof (edges [0]), CMP); maxedge = 0; num = 0; Kruskal (); cout <maxedge <Endl; cout <num <Endl; For (INT I = 0; I <num; I ++) {cout <edges [ans [I]. U <"" <edges [ans [I]. v <Endl ;}} return 0 ;}

Related Keywords:

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.