Agri-Net POJ

来源:互联网 发布:c语言编程器下载 编辑:程序博客网 时间:2024/05/01 05:08
Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms. 
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm. 
The distance between any two farms will not exceed 100,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 N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input
40 4 9 214 0 8 179 8 0 1621 17 16 0
Sample Output
28
#include<stdio.h>#include<string.h>#include<iostream>#include<algorithm>using namespace std;int b[1000][1000];int main(){    int a[1000],mark[1000];    int n,i,j,k,min,s;    while(scanf("%d",&n)!=EOF)    {        if(n==0){break;}        memset(b,0,sizeof(b));        memset(a,0,sizeof(a));        memset(mark,0,sizeof(mark));        for(i=1;i<=n;i++)        {            for(j=1;j<=n;j++)            scanf("%d",&b[i][j]);        }        k=1;s=1;       for(j=1;j<=n;j++)            {                mark[k]=2;min=9999999999;                 for(i=1;i<=n;i++)                {                    if(b[k][i]!=0&&(a[i]>b[k][i]||a[i]==0)&&mark[i]!=2)                    {                        a[i]=b[k][i];                        mark[i]=1;                    }                    if(b[i][k]!=0&&(a[i]>b[i][k]||a[i]==0)&&mark[i]!=2)                    {                        a[i]=b[i][k];                        mark[i]=1;                    }                }                for(i=1;i<=n;i++)                {                    if(a[i]!=0&&a[i]<min&&mark[i]==1)                    {                        min=a[i];                        s=i;                    }                }                k=s;            }            int ans=0;            for(i=1;i<=n;i++)            {                if(a[i]>0)                ans=ans+a[i];            }            printf("%d\n",ans);    }    return 0;}

原创粉丝点击