Hangzhou Electric Acm1301--jungle roads~~ minimum spanning tree

Source: Internet
Author: User

This question, simple minimal spanning tree problem.

Just enter the time is more troublesome, the beginning of N, is the number of villages, the following N-1 information, the beginning of the capital letter S and K, is the S village has a k road connection, followed by the K village and the weight value.

It's easy to handle the data you've entered.

The following is the code for the AC:

#include <iostream> #include <cstdio> #include <cstring> #include <algorithm>using namespace Std;class Data{public:int from, to, cost;}; Data road[100];int N, count1;int par[30];int cmp (data &a, data &b)//weights from small to large rows {return A.cost < B.cost ;} int finds (int x)//And look up the function {if (par[x] = = x) return X;elsereturn par[x] = finds (Par[x]);} void unite (int x, int y)//merge function {x = finds (x); y = finds (y); if (x = = y) return;elsepar[y] = x;} int same (int x, int y)//determine if the same and check set {return finds (x) = = finds (y);} int solve ()//constructs the minimum spanning tree function {int res = 0;for (int i = 0; i < count1; i++) {Data d = road[i];if (!same (d . From, D.to)) {Unite (d.from, d.to); res + = D.cost;}} return res;}       int main () {//freopen ("Data.txt", "R", stdin); int I, J, K, A, W;char s;while (scanf ("%d", &n)! = EOF && N) The input processing {getchar (); count1 = 0;for (i = 0; i <; i++) Par[i] = i;for (i = 0; i < n-1; i++) {scanf ("%c%d", &s, &am P;kA = S-' a '; GetChar (); for (j = 0; J < K; J + +) {scanf ("%c%d", &s, &w); Road[count1].from = A; Road[count1].to = S-' A '; Road[count1].cost = W;count1++;getchar ();}} Sort (road, road + COUNT1, CMP), int ans = solve ();p rintf ("%d\n", ans);} return 0;}


Hangzhou Electric Acm1301--jungle roads~~ 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.