https://vjudge.net/problem/hdu-1863
kruskal 算法是根据边来进行一条一条地往生成树中添加的,然后只有边的两点属于不同集合的边才能加入生成树中;
想过用vis数组标记然后进行看是否都用过了,如果都用过了,就不加入生成树中;后面想想是我想错了,如果出现两个最小树的情况,如果不把这两个树连在一起的话就不是最小生成树了;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
const ll maxn = 1000 + 10;
int n,m;
struct Node
{
int x,y,z;
}a[maxn];
bool cmp(const Node &x,const Node &y)
{
return x.z < y.z;
}
int fa[maxn];
void Init()
{
for(int i = 0; i< maxn; i ++)
fa[i] = i;
}
int finds(int x)
{
return x == fa[x] ? x : (fa[x] = finds(fa[x]));
}
int main()
{
while( ~ scanf("%d%d",&n,&m) && n)
{
for(int i = 1; i <= n; i ++)
{
scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);
}
Init();
sort(a+1,a+n+1,cmp);
int ans = 0;
int cnt = 0;
for(int i = 1; i <= n; i ++)
{
int x = finds(a[i].x);
int y = finds(a[i].y);
if(x != y)
{
fa[x] = y;
ans += a[i].z;
cnt ++;
}
if(cnt == m - 1)
{
cout << ans << endl;
break;
}
}
if(cnt != m - 1)
cout << "?" << endl;
}
return 0;
}