填坑...P1546 最短网络 Agri-Net

 P1546 最短网络 Agri-Net

  • 难度普及/提高-
  • 时空限制1s / 128MB

题目背景

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

题目描述

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

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

输入输出格式

输入格式:

 

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

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

 

输出格式:

 

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

 

输入输出样例

输入样例#1:
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
输出样例#1:
28

说明

题目翻译来自NOCOW。

USACO Training Section 3.1

思路分析:这个题好像是一本通上的题目,好久好久了。

连通性问题用Kruskal不错,然而这题用Prim更优。

基本就是套板子。

代码很丑(因为封装了很多东西)。

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 #define maxn 10005
 5 struct UnionFindSet
 6 {
 7     int x,y,v;
 8     int fat[maxn];
 9     UnionFindSet()
10     {
11         for(int i=0;i<maxn;i++)
12             fat[i]=i;
13         x=y=v=0;
14     }
15     inline int father(int x)
16     {
17         if(fat[x]!=x)
18             fat[x]=father(fat[x]);
19         return fat[x];
20     }
21     inline void unionn(int x,int y)
22     {
23         int fa=father(x);
24         int fb=father(y);
25         if(fa!=fb)
26             fat[fa]=fb;
27     }
28 };
29 struct Edge
30 {
31     int pre,to,w;
32     bool operator < (const Edge &b) const
33     {
34         return this->w < b.w;
35     }
36 };
37 Edge edge[maxn];
38 int cnt;
39 inline void AddEdge(int u,int v,int w)
40 {
41     edge[++cnt].pre=u;
42     edge[cnt].to=v;
43     edge[cnt].w=w;
44 }
45 UnionFindSet s;
46 int Kruskal(int EdgeNumber)
47 {
48     sort(edge+1,edge+1+EdgeNumber);
49     int n=1,ans=0;
50     while(n<EdgeNumber-1)
51     {
52         if(s.father(edge[n].pre)!=s.father(edge[n].to))
53         {
54             s.unionn(edge[n].pre,edge[n].to);
55             ans+=edge[n].w;
56         }
57         n++;
58     }
59     return ans;
60 }
61 int main()
62 {
63     int n,t;
64     scanf("%d",&n);
65     for(int i=1;i<=n;i++)
66         for(int j=1;j<=n;j++)
67         {
68             scanf("%d",&t);
69             if(t)
70                 AddEdge(i,j,t);
71         }
72     printf("%d\n",Kruskal(n*n-n));
73     return 0;
74 }
View Code

 

posted @ 2017-07-19 10:58  baka  阅读(198)  评论(0编辑  收藏  举报