The general minimum spanning tree algorithm is divided into two kinds of algorithms:
One is the Kruskal algorithm: the idea of this algorithm is to use the idea of greed, the weight of each side of the first order, and then each time to select the current minimum edge, to determine whether this side of the point has been selected, that is already in the tree, is generally used and check set to determine whether the two points have been connected;
Another algorithm is the PRIMM algorithm: This algorithm long thief like Digestala algorithm, first select a point to enter the set, and then find the point of connection points inside the value of the smallest point, and then each time in the selection and the set at any point connected to the edge of the minimum weight of the one (this operation can be modified in the relaxation, This is also the biggest difference with the Digestala algorithm, you choose a point after each, the point can reach the point of the weight of the edge of the value modified, rather than as the Digestala algorithm, the relaxation of the single-point weight value);
Kruskal Code:
#include <iostream>
#include <algorithm>
#define MAXN 5005
using namespace std;
struct Node
{
int x;
int y;
int w;
} NODE[MAXN];
Int cmp (Node x,node y)
{
return x.w<y.w;
}
Int FA[MAXN];
int Findfa (int x)
{
if (fa[x]==x)
return x;
Else
return Findfa (Fa[x]);
}
int join (int u,int v)
{
int t1,t2;
T1=findfa (U);
T2=findfa (v);
if (t1!=t2)
{
Fa[t2]=t1;
return 1;
}
Else
return 0;
}
Int main ()
{
int i,j;
int sum;
int ans;
int n,m;
sum=0;ans=0;
cin>>n>>m;
fo R (i=1;i<=m;i++)
Cin>>node[i].x>>node[i].y>>node[i].w;
Sort (node+1,node+1+m,cmp);
for (i=1;i<=n;i++)
Fa[i]=i,
for (i=1;i<=m;i++)
{
if (join (NODE[I].X,NODE[I].Y))
{
sum++;
ANS+=NODE[I].W;
}
if (sum==n-1)
break;
}
cout<<ans<<endl;
return 0;
}
Primm algorithm:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#define INF 0x3f3f3f
using namespace Std;
int map[1005][1005];
int dist[1005];
int visit[1005];
int n,m;
int prime (int x)
{
int temp;
int lowcast;
int sum=0;
memset (visit,0,sizeof (visit));
for (int i=1;i<=n;i++)
Dist[i]=map[x][i];
Visit[x]=1;
for (int i=1;i<=n-1;i++)
{
Lowcast=inf;
for (int j=1;j<=n;j++)
if (!visit[j]&&dist[j]<lowcast)
{
LOWCAST=DIST[J];
Temp=j;
}
Visit[temp]=1;
Sum+=lowcast;
for (int j=1;j<=n;j++)
{
if (!visit[j]&&dist[j]>map[temp][j])
DIST[J]=MAP[TEMP][J];
}
}
return sum;
}
int main ()
{
int y,x,w,z;
scanf ("%d%d", &n,&m);
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
{
if (I==J)
map[i][j]=0;
Else
Map[i][j]=inf;
}
}
memset (dist,inf,sizeof (Dist));
for (int i=1;i<=m;i++)
{
scanf ("%d%d%d", &x,&y,&w);
Map[x][y]=w;
Map[y][x]=w;
}
Z=prime (1);
printf ("%d\n", z);
return 0;
}
Minimum spanning tree algorithm (Kruskal algorithm and Primm algorithm)