前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >P1546 最短网络 Agri-Net

P1546 最短网络 Agri-Net

作者头像
attack
发布2018-04-13 11:16:35
5110
发布2018-04-13 11:16:35
举报

题目背景

农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。

题目描述

约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。

你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000

输入输出格式

输入格式:

第一行: 农场的个数,N(3<=N<=100)。

第二行..结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。

输出格式:

只有一个输出,其中包含连接到每个农场的光纤的最小长度。

输入输出样例

输入样例#1:

代码语言:javascript
复制
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

输出样例#1:

代码语言:javascript
复制
28

说明

题目翻译来自NOCOW。

USACO Training Section 3.1

裸的kurskal,注意fa数组一定要开的够大!

代码语言:javascript
复制
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<algorithm>
 6 using namespace std;
 7 const int MAXN=4001;
 8 void read(int & n)
 9 {
10     char c='+';int x=0;
11     while(c<'0'||c>'9')c=getchar();
12     while(c>='0'&&c<='9')
13     x=x*10+(c-48),c=getchar();
14     n=x;
15 }
16 struct node
17 {
18     int u,v,w,nxt;
19 }edge[MAXN*5];
20 int head[MAXN];
21 int num=1;
22 void add_edge(int x,int y,int z)
23 {
24     edge[num].u=x;
25     edge[num].v=y;
26     edge[num].w=z;
27     edge[num].nxt=head[x];
28     head[x]=num++;
29 }
30 int fa[MAXN*6];
31 int n;
32 inline int comp(const node &a ,const node & b)
33 {
34     return a.w<b.w;
35 }
36 inline int find(int x)
37 {
38     if(fa[x]!=x)
39     return fa[x]=find(fa[x]);
40     return fa[x];
41 }
42 inline void unionn(int x,int y)
43 {
44     int fx=find(x);
45     int fy=find(y);
46     fa[fx]=fy;
47 }
48 inline void kruskal()
49 {
50     int tot=0;
51     int ans=0;
52     sort(edge+1,edge+num,comp);
53     for(int i=1;i<=num-1;i++)
54     {
55         int now=edge[i].u;int will=edge[i].v;
56         if(find(now)!=find(will))
57         {
58             unionn(now,will);
59             tot++;
60             ans+=edge[i].w;
61         }
62         if(tot==n-1)
63         break;
64     }
65     printf("%d",ans);
66 }
67 int main()
68 {
69     //freopen("agrinet.in","r",stdin);
70     //freopen("agrinet.out","w",stdout);
71     read(n);
72     for(int i=0;i<=n;i++)
73         fa[i]=i;
74     for(int i=1;i<=n;i++)
75         for(int j=1;j<=n;j++)
76         {
77             int x;
78             read(x);
79             if(x!=0)
80             add_edge(i,j,x);
81         }
82     kruskal();
83     return 0;
84 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-06-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目背景
  • 题目描述
  • 输入输出格式
  • 输入输出样例
  • 说明
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档