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;
}