洛谷P2330 [SCOI2005]繁忙的都市 最小生成树模板题

题目链接:https://www.luogu.com.cn/problem/P2330

题目第一条件要让所有交叉路口连接起来,这就是要让图上所有点连通。第二个条件要用最少道路,显而易见是找生成树。第三个条件要使分值最大的道路分值尽量小,就是要找最小生成树。这里我用的是kruskal算法,最后一条被添加的边的长度就是生成树中分值最大的边。
代码如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=305;
const int inf=0xfffffff;
struct node
{
    int from;
    int to;
    int cost;
    friend bool operator < (node a,node b)
    {
        return a.cost > b.cost;
    }
}p;
int fa[maxn];
int n,m;
priority_queue<node>q;//优先队列
int find(int x)
{
    if(x==fa[x])
    return x;
    return fa[x]=find(fa[x]);
}
int kruskal()//求生成树
{
    int ans=0;
    while(!q.empty())
    {
        node temp=q.top();
        q.pop();
        int x=temp.from,y=temp.to,c=temp.cost;
        int xx=find(x),yy=find(y);
        //cout<<x<<" "<<y<<endl;
        //cout<<fa[x]<<" "<<fa[y]<<endl;
        if(xx!=yy)
        ans=c,fa[xx]=yy;//加入生成树,更新最大值
        //cout<<ans<<endl;
    }
    return ans;
}
int main()
{
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
    fa[i]=i;//初始祖先节点是自己
    for(int i=1;i<=m;i++)
    {
        scanf("%d %d %d",&p.from,&p.to,&p.cost);
        q.push(p);
    }
    printf("%d %d\n",n-1,kruskal());
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44491423/article/details/104463057