P1669 题解

· · 题解

题目传送门 题解传送门 更好的食用

题目大意

求最大生成树。

题目思路

本质上就是把最小生成树的排序部分改成降序排序,因此,这里使用 Kruskal。

但是判环部分不能直接判断节点 1 和节点 n 是否同祖宗,要判断是否能由 n 个点组成。

Kruskal 的基本思路是每次取出最小或最大的边,听起来挺麻烦,其实一个排序加一个遍历就搞定了。

当然用 Prim 也可以,但是对于不保证稠密的随机图,简单的 Kruskal 显然更适合。

参考代码

#include<bits/stdc++.h>
#define int long long
#define bt bitand
using namespace std;
struct node
{
    int u,v,w;
}a[222222];
int n,m,su,f[6666],j;
bool cmp(node a,node b)
{
    return a.w>b.w;
}
int find(int x)
{
    if(x==f[x])return x;
    else return f[x]=find(f[x]);
}
void kruskal()
{
    sort(a+1,a+1+m,cmp);
    for(int i=1;i<=m;i++)
    {
        int x=find(a[i].u),y=find(a[i].v);
        if(x!=y)
        {
            su+=a[i].w,j++;
            f[x]=y;
        }
    }
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)scanf("%lld %lld %lld",bt a[i].u,bt a[i].v,bt a[i].w);
    for(int i=1;i<=n;i++)f[i]=i;
    kruskal();
    if(j==n-1)cout<<su;
    else cout<<"-1";
    return 0;
}