洛谷P1547 Out of Hay kruskal

传送门

最小生成树模板题

#include<iostream>
#include<algorithm>
using namespace std;
int n,m;
int par[2005];
struct pp
{
    int from,to,w;
}e[10005];
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]);
}
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);
    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<<e[i].w<<endl;
            return;
        }
    }
}
int main()
{
    solve();
}

猜你喜欢

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