洛谷 P1546 最短网络 Agri-Net 最小生成树
题目背景
农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。
题目描述
约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。
你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000
输入格式
第一行: 农场的个数,N(3<=N<=100)。
第二行..结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。
输出格式
只有一个输出,其中包含连接到每个农场的光纤的最小长度。
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e5+5;
int father[maxn];
int map[105][105];
struct node{
int from;
int to;
int len;
}stc[10005];
bool cmp(node a, node b)
{
return a.len<b.len;
}
void init()
{
for(int i=1;i<maxn;++i)
{
father[i]=i;
}
}
int find(int x)
{
if(x==father[x])
{
return x;
}
return father[x] = find(father[x]);
}
void merge(int x,int y)
{
int p = find(x);
int q = find(y);
if(p!=q)
{
father[p]=q;
}
}
bool judge(int x,int y)
{
int p = find(x);
int q = find(y);
if(p!=q)
{
return true;
}
return false;
}
int main()
{
int n;
while(cin>>n)
{
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
{
cin>>map[i][j];
}
}
int top=0;
for(int i=0;i<n;++i)
{
for(int j=i;j<n;++j)
{
stc[top].from = i;
stc[top].to = j;
stc[top++].len = map[i][j];
}
}
sort(stc,stc+top,cmp);
init();
int ans = 0;
int m=0;
for(int i=0;i<top;++i)
{
if(judge(stc[i].from,stc[i].to)) //不在一个集合的时候
{
merge(stc[i].from,stc[i].to);
ans+=stc[i].len;
m++;
if(m==n-1)
{
break;
}
}
}
cout<<ans<<endl;
}
return 0;
}