Kruskal
用来求最小生成树的,把所有边放进小根堆,依次取出,要是不会和现有的最小生成树形成环路,就把这个边加入最小生成树
下方的是板子,顺便体现了怎么记录一个并不联通的图最小生成树后还剩几个类
ll bingchaji[10000000] = {0};
ll find(ll x)
{
return x == bingchaji[x] ? x : bingchaji[x] = find(bingchaji[x]);//第二个是返回赋的值
}
priority_queue<pair<ll, pair<ll, ll>>> v;
for (ll i = 0; i < m; i++)
{
ll a, b, c;
cin >> a >> b >> c;
v.push(pair<ll, pair<ll, ll>>(-c, pair<ll, ll>(a, b))); //创建小根堆,权重是c,从a到b的边
}
for (ll i = 1; i <= n; i++) //初始化并查集
{
bingchaji[i] = i;
}
ll tn = n; //记录还有几个类簇,最开始是点的数量
for (ll i = 0; i < n; i++)
{
ll c = v.top().first;
ll a = v.top().second.first;
ll b = v.top().second.second;
v.pop();
ll k = find(a);
ll kk = find(b);
if (k != kk) //能形成环路就不要添加了
{
bingchaji[kk] = k; //合并节点
tn--;
}
}