Poj2421 constructing roads

Source: Internet
Author: User

Description:

There are n villages numbered 1, 2, 3, and n that should be built to make them accessible to each other.

Input data

 
30 990 692990 0 179692 179 2

Three villages,

 
0 990 692990 0 179692 179 0

The distance from 1 to 1, 2, and 3 is 0, 990, 692, respectively.

 
11 2

It means there is a road connected, that is, the road between 1 and 2.

Solution:

KruskalAlgorithmTo build the Minimum Spanning Tree.

# Include <algorithm> # include <iostream> # include <vector> using namespace STD; Class Road // defines the data type of the road {public: int L, R; int dis ;}; vector <road> A; // store the input road int parent [200]; // check the structure of the set, parent [I] indicates the parent node of I int root (int A) // query the root node of A {If (parent [a] = A) {return ;} return parent [a] = root (parent [a]);} void Merge (int A, int B) // combine the collection of a and B {int Ra = root (a); int RB = root (B); parent [Ra] = RB ;} bool CMP (Road A, road B) // sorting function {return. dis <B. DIS ;} Int main () {int N; CIN> N; For (INT I = 0; I <n; I ++) {parent [I] = I; // check the initialization of the Set} For (INT I = 0; I <n; I ++) {road TMP; TMP. L = I; for (Int J = 0; j <n; j ++) {TMP. R = J; CIN> TMP. DIS;. push_back (TMP) ;}} int Q; CIN >> Q; while (Q --) {int L, R; CIN >>> l >> R; merge (L-1, r-1);} Sort (. begin (),. end (), CMP); // sort int size =. size (); int ans = 0; For (INT I = 0; I <size; I ++) {If (root (A [I]. l )! = Root (A [I]. r) // if not in the same set {merge (A [I]. l, a [I]. r); ans + = A [I]. dis ;}} cout <ans <Endl; return 0 ;}

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.