【SSL】1682最短网络 (最小生成树)

【SSL】1682最短网络 (最小生成树)

Time Limit:1000MS
Memory Limit:65536K

Description

农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000

Input

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

Output

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

Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

Sample Output

28

思路

用kruskal和并查集。

代码

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
int n,ans=0,tot=0,b[110];
struct jgt
{
    
    
	int x,y,w;
}f[10010];
bool cmp(jgt t1,jgt t2)
{
    
    
	return t1.w<t2.w;
}
void input()
{
    
    
	int i,j,t;
	scanf("%d",&n);
	for(i=1;i<=n;b[i]=i,i++)
		for(j=1;j<=n;j++)
		{
    
    
			scanf("%d",&t);
			if(t)	
			{
    
    
				tot++;
				f[tot].x=i;
				f[tot].y=j;
				f[tot].w=t;
			}
		}
	return;
}
int bcj(int x)
{
    
    
	if(b[x]==x)return x;
	return b[x]=bcj(b[x]);
}
void kruskal()//最小生成树 
{
    
    
	int i;
	sort(f+1,f+tot+1,cmp);//排序 
	for(n--,i=0;n;i++)
	{
    
    
		if(bcj(f[i].x)!=bcj(f[i].y))
		{
    
    
			n--;
			ans+=f[i].w;
			b[bcj(f[i].x)]=bcj(f[i].y);
		}
	}
	return;
}
int main()
{
    
    
	input();
	kruskal();
	printf("%d",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46975572/article/details/112973203