Agri-Net

传送门

题目描述:
Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.

输入:
输入包括几个案例。对于每个案例,第一行包含农场的数量,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

题目大意 :有n块地方要求使每两个之间必须有路(可以a到b,可以a到c、b到c,也算a到b);求出最短的路程是多少。

思路:用ant[N]存储到每个点的距离,遍历出最短距离然后加起来就是最终结果。

代码:

#include<iostream>
using namespace std;
#define ll long long
#include<cstring>
const ll N=105;
int n;
ll a[N][N];
ll ant[N];
ll as[N];

ll prim()
{
	ll ans=0;
	memset(ant,0x3f,sizeof ant);
	memset(as,0,sizeof as);
	for(int i=0;i<n;i++)
	{
		int t=-1;
		for(int j=0;j<n;j++)
		{
			if(as[j])continue;
			if(t==-1)t=j;
			else if(ant[t]>ant[j])t=j;
		}
		as[t]=1;
		if(i==0)ans+=0;
		else ans+=ant[t];
		
		for(int j=0;j<n;j++)
		{
			ant[j]=min(ant[j],a[t][j]);
		}
	}
	return ans;
}



int main()
{
	while(cin>>n)
	{
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
			{
				cin>>a[i][j];
			}
		}
		cout<<prim()<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值