概述
《POJ 1258 - 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.
Input
The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output
28
题目的大意
在翻译了在翻译了.jpg
那个,大意是给出N个点,然后下面N行,第1行第2个就是点1到点2的距离,
第2行第1个就是点2到点1的距离,以此类推,然后我们要做的事情是用最短的总长度
把它们连在一起。
解题思路和方法
嗯...应该是找出每个点连接下一个点的最短距离就好了吧
主要函数需要用到的代码
void prime()
{
int i,j,h;
memset(vis,0,sizeof(vis));
for(i=1;i<=n;i++) dis[i]=map[1][i];
dis[1]=0;
vis[1]=1;
int p;
for(j=1;j<n;j++)
{
int minx=0x3f3f3f3f;
p=-1;
for(i=1;i<=n;i++)
{
if(!vis[i]&&dis[i]<minx)
{
minx=dis[i];
p=i;
}
}
vis[p]=1;
ans+=dis[p];
for(i=1;i<=n;i++)
{
if(!vis[i]&&map[p][i]<dis[i])
{
dis[i]=map[p][i];
}
}
}
}
完整代码
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int n;
int map[101][101]; //用map数组来记录之前那个图的矩阵
int ans;
int vis[101],dis[101]; //然后呢,用vis数组来判别这个点是否已经被连接
// dis数组就是目前所尚未连接的点的最短距离
void prime()
{
int i,j,h;
memset(vis,0,sizeof(vis));
for(i=1;i<=n;i++) dis[i]=map[1][i];
dis[1]=0;
vis[1]=1;
int p;
for(j=1;j<n;j++)
{
int minx=0x3f3f3f3f;
p=-1;
for(i=1;i<=n;i++)
{
if(!vis[i]&&dis[i]<minx)
{
minx=dis[i];
p=i;
}
}
vis[p]=1;
ans+=dis[p];
for(i=1;i<=n;i++)
{
if(!vis[i]&&map[p][i]<dis[i])
{
dis[i]=map[p][i];
}
}
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
int i,j;
ans=0;
memset(dis,0x3f,sizeof(dis));
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&map[i][j]);
}
}
prime();
printf("%dn",ans);
}
return 0;
}
最后
以上就是专注店员为你收集整理的《POJ 1258 - Agri-Net》的题解《POJ 1258 - Agri-Net》的题解的全部内容,希望文章能够帮你解决《POJ 1258 - Agri-Net》的题解《POJ 1258 - Agri-Net》的题解所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复