[Codevs 1231] optimal wiring problem, codevs1231
DescriptionDescription
The school needs to connect n computers. The cost of connecting two computers may be different. To save costs, we consider ending indirect data transmission, that is, one computer can be indirectly connected to another computer through other computers.
To connect any two computers (whether directly or indirectly), you need to directly connect several computers with a network cable. Now you want to minimize the total cost of connection, let you program and calculate the minimum cost.
Input description
Input Description
Enter the first two integers n, m (2 <= n <= 100000,2 <= m <= 100000), indicating the total number of computers and the number of connections that can be established with each other. In the next m row, three integers a, B, and c in each row indicate that the call charge for establishing a connection between machine a and machine B is c. (The question must have a feasible Connectivity Solution. The data may have duplicate edges with different weights, but there is no self-ring)
Output description
Output Description
There is only one integer in the output line, indicating the lowest total connection fee.
Sample Input
Sample Input
3 3
1 2 1
1 3 2
2 3 1
Sample output
Sample Output
2
Data range and prompt
Data Size & Hint
The final answer must be saved using the long type.
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 #define maxn 100005 6 using namespace std; 7 int fa[maxn],deep[maxn]; 8 int n,m,tot=0;long long ans=0; 9 struct node{int u,v,w;}e[maxn];10 bool cmp(node a,node b){return a.w<b.w;}11 int find(int x){12 if(fa[x]==x) return x;13 else return fa[x]=find(fa[x]);14 }15 void unite(int x,int y){16 x=find(x),y=find(y);17 if(x==y) return ;18 if(deep[x]<deep[y]) fa[x]=y;19 else{20 fa[y]=x;21 if(deep[x]==deep[y]) deep[y]++;22 }23 }24 bool same(int a,int b){25 return find(a)==find(b);26 }27 int main(){28 scanf("%d%d",&n,&m);29 for(int i=1;i<=n;i++) fa[i]=i,deep[i]=0;30 for(int i=1;i<=m;i++) scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);31 sort(e+1,e+m+1,cmp);32 for(int i=1;i<=m;i++){33 if(same(e[i].u,e[i].v)) continue;34 else{35 unite(e[i].u,e[i].v);36 ans+=e[i].w;37 tot++;38 }39 }40 printf("%lld",ans);41 return 0;42 }