Optimal cabling problem (Kruskal algorithm)
Time limit: 1 s
Space limit: 128000 KB
Title Level: Silver
Exercises
View Run Results
Title Description Description
Schools need to connect n computers, and the cost of connection between the different 2 computers may be different. To save money, we consider the end of indirect data transfer, where one computer can indirectly connect to another computer via another computer.
In order for any two computers to be connected (whether directly or indirectly), you need to use a network cable between several computers directly connected, now want to make the total cost of connection is the most province, let you program to calculate this minimum cost.
Enter a description Input Description
Enter the first behavior two integer n,m (2<=n<=100000,2<=m<=100000), which represents the total number of computers, and the number of connections that can be connected to each other. Next m line, three integers per line a,b,c means that the charge for establishing a connection between machine A and machine B is c. (the topic guarantees that there must be a viable connectivity scheme, the data may have a different weight, but no self-loop)
Output Description Output Description
The output is an integer that represents the total connection cost for the most province.
Sample Input Sample Input
3 3
1 2 1
1 3 2
2 3 1
Code:
#include
using namespace Std;
#include
#include
#include
#define MAXN 100001
#define INF 0x7fffffff
int n,m,a,b,c;
Long long Tot=0;//long long to save
int father[maxn]={0};
struct edge{
int u,v,w,next;
};
Edge EDGE[MAXN];
void input ();
void Krsual ();
int main ()
{
Input ();
Krsual ();
printf ("%lld\n", tot);
return 0;
}
int cmp (const edge &a,const edge &b)
{
Return A.W
}
void input ()
{
scanf ("%d%d", &n,&m);
for (int i=1;i<=m;++i)
Edge[i].w=inf;
for (int i=1;i<=m;++i)
{
scanf ("%d%d%d", &a,&b,&c);
if (edge[i].w>c)
{
Edge[i].w=c;
Edge[i].u=a;
Edge[i].v=b;
Edge[i+m].w=c; (the side table that handles the non-map, plus m on it)
Edge[i+m].v=a;
Edge[i+m].u=b;
}
}
}
int find (int x)
{
if (father[x]!=x) Father[x]=find (father[x]);
return father[x];
}
void Unionn (int r1,int R2)
{
FATHER[R2]=R1;
}
int k=0;
void Krsual ()
{
for (int i=1;i<=n;++i)
Father[i]=i;
Sort (edge+1,edge+m+1,cmp);
for (int i=1;i<=m;++i)//go through all the edges again
{
int R1=find (EDGE[I].U);
int R2=find (EDGE[I].V);
if (R1!=R2)//Note and look up merge and find are all looking for the set of Representative elements
{
Unionn (R1,R2);//not merging two points, is merging the representative elements
TOT+=EDGE[I].W;
k++;
if (k==n-1) return;//count, n-1 the edge is enough
}
}
}
19. Optimal cabling problem (Kruskal algorithm)