【北大 夏令营笔记-最小生成树】poj1258-Agri-Net

Agri-Net
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 39063 Accepted: 15817
Description

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

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output

28
Source

USACO 102




最小生成树裸题
Prim算法

AC代码:

#include<stdio.h>
#include<algorithm>
using namespace std;
struct Edge
{
   int a;
   int b;
   int len;
}per[10010];
int flag[10010];
int cmp(Edge x,Edge y)
{
   if(x.len!=y.len) return x.len<y.len;
}
int main()
{
    int i,j,n,m,k,sum,num;
    while(scanf("%d",&n)!=EOF)
    {
       memset(per,0,sizeof(per));
       k=0;
       for(i=0;i<n;i++)
         for(j=0;j<n;j++)
         {
            scanf("%d",&per[k].len);
            per[k].a=i+1;
            per[k++].b=j+1;
         }
       sort(per,per+k,cmp);
       for(i=1;i<=n;i++)
       flag[i]=1;
       flag[per[0].a]=0;
       sum=0;
       for(i=0;i<k;i++)
       {
          num=flag[per[i].a]+flag[per[i].b];
          if(num==1)
          {
             sum+=per[i].len;
             flag[per[i].a]=flag[per[i].b]=0;
             i=0;
          }
       }
       printf("%d\n",sum);
    }
    return 0;
}

上一篇:LeetCode OJ:Subsets II


下一篇:《数据结构与算法 C语言版》—— 1.7上机实验