51nod 1212 Graph-Free minimum spanning tree (Kruskal)

Source: Internet
Author: User


The undirected graph of the N-point M-edge, with a weighted value for each edge, to find the smallest spanning tree of the graph. Input

Line 1th: 2 number n,m The middle is separated by a space, N is the number of points, and M is the number of edges. (2 <= N <=, 1 <= M <= 50000)
2-m + 1 lines: 3 number s E W per line, respectively, representing 2 vertices and weights for M-bar edges. (1 <= S, E <= n,1 <= W <= 10000)
Output
Outputs the sum of weights for all edges of the minimum spanning tree.
Input example
9
1 2 4
2 3 8
3 4 7
4 5 9 5 6 6
7 2
7 8 1
8 9 7 2
8 each
3 9
2 7 9 6
  3 6 4
4 6
1 8 8
Output example
37

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int fa[1111];

void init (int n)
{for
	(int i=0;i<=n;i++) fa[i]=i;
}

int find (int x)
{
	int r;
	r=x;
	while (FA[R]!=R) r=fa[r];
	int i=x,j;
	while (i!=r) {
		j=fa[i];
		Fa[i]=r;
		i=j;
	}
	return r;
}
struct node
{
	int u;
	int V;
	int num;
} A[55555];

BOOL CMP (node X,node y)
{
	if (x.num<y.num) return true;
	return false;
}

int main ()
{
	 Ios::sync_with_stdio (false);  
	int I,j,n,m,ans;
	ans=0;
	cin>>n>>m;
	Init (n);
	for (i=0;i<m;i++) {
		cin>>a[i].u>>a[i].v>>a[i].num;
	}
	Sort (a,a+m,cmp);
	for (i=0;i<m;i++) {
		int fx=find (A[I].U);
		int Fy=find (A[I].V);
		if (fx!=fy) {
			fa[fx]=fy;
			Ans+=a[i].num;
		}
	}
	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.