[usaco3.1.1]agrinet

博客介绍了一道最小生成树的模板题,作者借此学习了刘汝佳的间接排序和Kruskal算法,还给出了转载链接。

   是一道最小生成树的模板题,顺便学习了一下刘汝佳大大的间接排序和Kruskal算法。

/*
ID:abc31261
LANG:C++
TASK:agrinet 
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn=11111;
int r[maxn],f[maxn],w[maxn],u[maxn],v[maxn];

int cmp(const int i,const int j){ return w[i]<w[j]; }      //间接排序 

int find(int x)
{
    if (f[x]!=x)f[x]=find(f[x]);
    return f[x];
}
int main()
{
    int i,j,l,x,y,n,m=0,ans=0;
    freopen("agrinet.in","r",stdin);
    freopen("agrinet.out","w",stdout);
    scanf("%d",&n);
    for (i=1;i<=n;i++)
        for (j=1;j<=n;j++)
        {
            scanf("%d",&l);
            w[++m]=l;
            u[m]=i;
            v[m]=j;
        }
    for (i=1;i<=m;i++)r[i]=f[i]=i;
    sort(r+1,r+m+1,cmp);
    for (i=1;i<=m;i++)
    {
        j=r[i]; x=find(u[j]); y=find(v[j]);
        if (x!=y) 
        {
           ans+=w[j];
           f[y]=x;
        }
    }
    printf("%d\n",ans);
    return 0;
}

 

转载于:https://www.cnblogs.com/Sun-Sea/p/5005889.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值