POJ  1258  Agri-Net

来源:互联网 发布:淘宝店高达 编辑:程序博客网 时间:2024/06/08 14:12
Agri-Net
Time Limit: 1000MSMemory Limit: 10000KTotal Submissions: 23043Accepted: 9079

Description

Farmer John has been elected mayor of his town!One of his campaign promises was to bring internet connectivity toall farms in the area. He needs your help, ofcourse. 
Farmer John ordered a high speed connection for his farm and isgoing to share his connectivity with the other farmers. To minimizecost, he wants to lay the minimum amount of optical fiber toconnect his farm to all the other farms. 
Given a list of how much fiber it takes to connect each pair offarms, you must find the minimum amount of fiber needed to connectthem all together. Each farm must connect to some other farm suchthat a packet can flow from any one farm to any otherfarm. 
The distance between any two farms will not exceed100,000. 

Input

The input includes several cases. For each case,the first line contains the number of farms, N (3 <=N <= 100). The following lines contain the N x Nconectivity matrix, where each element shows the distance from onfarm to another. Logically, they are N lines of N space-separatedintegers. Physically, they are limited in length to 80 characters,so some lines continue onto others. Of course, the diagonal will be0, since the distance from farm i to itself is not interesting forthis problem.

Output

For each case, output a single integer length thatis the sum of the minimum length of fiber required to connect theentire set of farms.

Sample Input

40 4 9 214 0 8 179 8 0 1621 17 16 0

Sample Output

28

Source

USACO 102
最小生成树,快排+并查集
代码:
C++语言: 临时自用代码
#include<stdio.h>
#include<stdlib.h>
struct point{
    int x,y,num;
}map[10008];
int flag[108];
int cmp(const void *a,const void *b)
{
    struct point *c,*d;
    c=(struct point *)a;
    d=(struct point *)b;
    return c->num-d->num;
}
int father(int x)
{
    if(x==flag[x])
        return x;
    flag[x]=father(flag[x]);
    return flag[x];
}
int main()
{
    int N,i,j,k,a,fa,fb,sum;
    while(scanf("%d",&N)!=EOF)
    {
        k=0;
        for(i=1;i<=N;i++)
        {
            flag[i]=i;
            for(j=1;j<=N;j++)
            {
                scanf("%d",&a);
                if(i<j){
                    map[k++].x=i;
                    map[k-1].y=j;
                    map[k-1].num=a;
                }
            }
        }
            qsort(map,k,sizeof(map[0]),cmp);
            sum=0;
            for(i=0;i<k;i++)
            {
                fa=father(map[i].x);
                fb=father(map[i].y);
                if(fa!=fb){
                    if(fa>fb)
                        flag[fa]=fb;
                    else flag[fb]=fa;
                    sum+=map[i].num;
                }
            }
            printf("%d\n",sum);
    }
    return 0;
}
原创粉丝点击