洛谷P2330 [SCOI2005]繁忙的都市 kruskal

传送门

kruskal的模板题

#include<iostream>
#include<algorithm>
using namespace std;
int n,m;
struct pp
{
    int from,to,w;
}e[100005];
int ans;
int par[100005];//并查集 
bool cmp(pp a,pp b)
{
    return a.w<b.w;
}
void init(int n)
{
    for(int i=1;i<=n;i++)par[i]=i;
}
int find(int x)
{
    if(x==par[x])return x;
    return par[x]=find(par[x]);//x的父亲指向树根 
}
void unite(int x,int y)
{
    x=find(x);
    y=find(y);
    if(x==y)return;
    par[x]=y;
}
bool same(int x,int y)
{
    return find(x)==find(y);
}
void solve()
{
    cin>>n>>m;
    init(n);//这句不能少!! 
    ans=n-1;
    for(int i=1;i<=m;i++)
    {
        cin>>e[i].from>>e[i].to>>e[i].w;
    }
    sort(e+1,e+1+m,cmp);
    for(int i=1;i<=m;i++)
    {
        if(same(e[i].from,e[i].to)!=true)
        {
            n--;//联通块减一 
            unite(e[i].from,e[i].to); 
        }
        if(n==1)
        {
            cout<<ans<<" "<<e[i].w<<endl;
            return;
        }
    }
}
int main()
{
    solve();
}

猜你喜欢

转载自www.cnblogs.com/lyhhahaha/p/10086178.html