COGS——T 7. 通信线路

http://www.cogs.pro/cogs/problem/problem.php?pid=7

★★   输入文件:mcst.in   输出文件:mcst.out   简单对比
时间限制:1.5 s   内存限制:128 MB

问题描述
假设要在n个城市之间建立通信联络网,则连通n个城市只需要n-1条线路。这时, 如何在最少经费的前提下建立这个通信网。在每两个城市之间都可以设置—条线路,相应地都要付出一定的经济代价。n个城市之间,最多可能设置n(n- 1)/2条线路,那么,如何在这些可能的线路中选择n-1条,以使总的耗费最少呢?
 
【输入格式】
输入文件有若干行
第一行,一个整数n,表示共有n个城市
第2--n+1行,每行n个数,分别表示该城市与其它城市之间路线的费用,如果城市间不能建立通信则用-1表示
 
【输出格式】
一行,1个整数,表示最少总费用
 
【输入输出样例】
 
输入文件
 

-1 5 -1 -1 -1 -1 
5 -1 50 -1 -1 10
-1 50 -1 20 10 -1
-1 -1 20 -1 60 30
-1 -1 10 60 -1 100
-1 10 -1 30 100 -1
 
输出文件
 
75
 
【数据规模】
 
对于40%的数据,保证有n<100: 
对于60%的数据,保证有n<256; 
对于全部的数据,保证有n<=1501。
 
 1 #include<algorithm>
 2 #include<cstdio>
 3 
 4 using namespace std;
 5 
 6 const int N(1506);
 7 int n,tot,fa[N];
 8 struct Edge
 9 {
10     int u,v,w;
11 } edge[N*N>>1];
12 bool cmp(Edge a,Edge b)
13 {
14     return a.w<b.w;
15 }
16 
17 int find(int x)
18 {
19     return fa[x]==x?x:fa[x]=find(fa[x]);
20 }
21 
22 inline void read(int &x)
23 {
24     x=0; int if_=0;char ch=getchar();
25     for(; ch<'0'||ch>'9'; ch=getchar()) if(ch=='-') if_=1;
26     for(; ch>='0'&&ch<='9'; ch=getchar()) x=x*10+ch-'0';
27     x=!if_?x:((~x)+1);
28 }
29 
30 int main()
31 {
32     freopen("mcst.in","r",stdin);
33     freopen("mcst.out","w",stdout);
34     read(n);
35     for(int x,i=1; i<=n; i++)
36         for(int j=1; j<=n; j++)
37         {
38             read(x);
39             if(x!=-1)
40             {
41                 edge[++tot].u=i,
42                 edge[tot].v=j;
43                 edge[tot].w=x;
44             }
45         }
46     for(int i=1; i<=n; i++) fa[i]=i;
47     sort(edge+1,edge+1+tot,cmp);
48     int cnt=0,ans=0;
49     for(int i=1; i<=tot; i++)
50     {
51         int x=edge[i].u,y=edge[i].v;
52         int fx=find(x),fy=find(y);
53         if(fx==fy) continue;
54         fa[fx]=fy;
55         ans+=edge[i].w;
56         if(++cnt==n-1) break;
57     }
58     printf("%d",ans);
59     return 0;
60 }
——每当你想要放弃的时候,就想想是为了什么才一路坚持到现在。
原文地址:https://www.cnblogs.com/Shy-key/p/7401482.html