码迷,mamicode.com
首页 > Web开发 > 详细

POJ 1258 Agri-Net

时间:2014-07-23 00:03:57      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   2014   for   re   

题意:就是要你求最小生成树所需的最小距离

思路:Kruskal算法

AC代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 125000
int u[N],v[N],w[N],r[N];
int f[520],str[520][520];
int find(int x)
{
    if(x!=f[x])
        f[x]=find(f[x]);
    return f[x];
}
int cmp(const int x,const int y)    //间接排序距离
{
    return w[x]<w[y];
}
int main()
{
    int x,y,sum,e,i,j,n;
    while(scanf("%d",&n)!=EOF)
    {
        int cnt=0;
        memset(str,0,sizeof(str));
        for(i=1;i<=n;i++)
            for(j=1;j<=n;j++)
            {
                int val;
                scanf("%d",&val);
                if(val==0)
                    continue;
                if(!(str[i][j]&&str[j][i]))
                {
                    u[cnt]=i;
                    v[cnt]=j;
                    w[cnt++]=val;
                    str[i][j]=str[j][i]=1;
                }

            }
        for(i=0;i<=n;i++)f[i]=i;
        for(i=0;i<=cnt;i++)r[i]=i;
        sort(r,r+cnt,cmp);
        sum=0;
        for(i=0;i<=cnt;i++)
        {
            e=r[i];
            x=find(u[e]);
            y=find(v[e]);
            if(x!=y){
                sum+=w[e];
                f[x]=y;
            }

        }
        printf("%d\n",sum);
    }
}


POJ 1258 Agri-Net,布布扣,bubuko.com

POJ 1258 Agri-Net

标签:style   blog   io   2014   for   re   

原文地址:http://blog.csdn.net/u012313382/article/details/38048457

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!