kruskal主要是建树过程中不能出现环，如果加入当前边，会形成环，就放弃这个边，继续向下建树。直到这个树

``````#include<stdio.h>
#include<string.h>
#include<algorithm>
#define mmset(a,b) memset(a,b,sizeof(a))
using namespace std;

const int N = 1005;

struct node
{
int x,y,w;
};
int father[N];
node edges[N*N];
int n,m, index = 1;

bool cmp(node a, node b)
{
return a.w < b.w;
}
void init()
{
for(int i = 1; i <= n; i++)
{
father[i] = i;
}
}

int find(int u)
{
if(u != father[u])
{
father[u] = find(father[u]);
}
return father[u];
}

void marge(int v,int u)
{
father[v] = u;
}

int main()
{
scanf("%d %d",&n,&m);
init();
index = 1;
for(int i = 1; i <= m; i++)
{
int x,y,w;
scanf("%d %d %d",&x,&y,&w);
edges[index].x = x, edges[index].y = y, edges[index++].w = w;

}

sort(edges + 1, edges + index, cmp);

int num = 1,res = 0;
for(int i = 1; i <= n-1; )
{
int x = edges[num].x, y = edges[num].y;
int mx = find(x), my = find(y);

if(mx != my)  //用并查集来判断是否成环。
{
marge(mx,my);
res += edges[num].w;
i++;   //如果不成环，这个树的边树就+1
}
num++;

}
printf("%d\n",res);

return  0;
} ``````