哈哈火的Blog

an oier

导航

<2026年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

常用链接

留言簿

文章分类

文章档案

搜索

最新评论

USACO 3.1.1 Agri-Net

Problem
Agri-Net
Russ Cox

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.

PROGRAM NAME: agrinet

INPUT FORMAT

Line 1:The number of farms, N (3 <= N <= 100).
Line 2..end:The subsequent lines contain the N x N connectivity 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.

SAMPLE INPUT (file agrinet.in)

4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0 

OUTPUT FORMAT

The single output contains the integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.

SAMPLE OUTPUT (file agrinet.out)

28
Solution这是最简单的MST(最小生成树问题)
应该用Prim算法.
下面直接上代码
#include <cstdio>
#define MAX 99999999
int a[200][200],que[200],top=0,book[200];
int main()
{
    freopen("agrinet.in","r",stdin);
    freopen("agrinet.out","w",stdout);
    
int min,min1,min2,all=0,n,i,j;
    scanf("%d",&n);
    
for(i=1;i<=n;i++)
        
for(j=1;j<=n;j++)
            a[i][j]=MAX;
    
for(i=1;i<=n;i++)
        
for(j=1;j<=n;j++)
            scanf("%d",&a[i][j]);
    top++;
    que[1]=1;
    book[1]=1;
    
while(top<n)
    {
        min=MAX;
        
for(i=1;i<=top;i++)
        {
            
for(j=1;j<=n;j++)
            {
                
if(book[j]==0 && a[que[i]][j]<min)
                {
                    min=a[que[i]][j];
                    min1=que[i];
                    min2=j;
                }
            }
        }
        top++;
        que[top]=min2;
        book[min2]=1;
        all+=min;
        a[min1][min2]=MAX;
        a[min2][min1]=MAX;
    }
    printf("%d\n",all);
    
return 0;
}

posted on 2011-12-04 19:58 哈哈火 阅读(98) 评论(0)  编辑 收藏 引用 所属分类: USACO


只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理