标签:log 包含 需要 模板题 names 方案 logs als using
农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。
约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。
你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000
输入格式:
第一行: 农场的个数,N(3<=N<=100)。
第二行..结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。
输出格式:
只有一个输出,其中包含连接到每个农场的光纤的最小长度。
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
28
与繁忙的都市类似,模板题。
#include<bits/stdc++.h> #define LL long long const int inf=20000000; using namespace std; LL n,m; struct Edge{LL from,to,w;}; struct Edge e[300000]; LL f[300000]; LL ans=0; bool cmp(const Edge &a,const Edge &b) { return a.w<b.w; } LL Find(LL x) {return f[x]==x?x:f[x]=Find(f[x]);} LL merge(LL x,LL y) { LL fx=Find(x),fy=Find(y); if(f[fx]!=fy) { f[fx]=fy; return 1; } return 0; } int main() { ios::sync_with_stdio(false); LL Count=0; cin>>n; LL x; for(LL i=1;i<=n*n;i++) { cin>>x; if(x!=0) {e[i].from=(i-1)/n+1;e[i].to=(i-1)%n+1;e[i].w=x;} else e[i].w=inf; } for(LL i=1;i<=n;i++) f[i]=i; sort(e+1,e+n*n+1,cmp); for(LL i=1;i<=n*n;i++) { if(merge(e[i].from,e[i].to)) { ans+=e[i].w; Count++; } if(Count==n-1) break; } cout<<ans<<endl; return 0; }
最小生成树基础模板题(USACO Training Section 3.1 最短网络 Agri-Net)
标签:log 包含 需要 模板题 names 方案 logs als using
原文地址:http://www.cnblogs.com/foreverpiano/p/6904804.html