最小生成树的个人见解及模板:
kruskal算法模板:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
int pre[100005];
int n,m;
struct node{
int u,v,w;
bool operator < (const node & rhs)
{
return w < rhs.w;
}
}e[1005];
void init()
{
for(int i = 1;i <= n;i++)
{
pre[i] = i;
}
}
int findx(int x)
{
return x == pre[x] ? x :pre[x] = findx(pre[x]);
}
void joint(int a,int b)
{
a = findx(a);
b = findx(b);
if(a == b)
{
return ;
}
else
{
pre[a] = b;
}
}
bool same(int u,int v)
{
return findx(u) == findx(v);
}
int main()
{
while(cin >> n >> m)
{
init();
for(int i = 0;i < m;i++)
{
cin >> e[i].u >> e[i].v >> e[i].w;
}
sort(e,e+m);
int ans = 0;
for(int i = 0;i < m;i++)
{
if(!same(e[i].u,e[i].v))
{
ans += e[i].w;
joint(e[i].u,e[i].v);
}
}
cout << ans << endl;
}
}