Description
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
Output
Sample Input
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
Sample Output
28
Source
#include <iostream>
#include <cstring>
using namespace std;
int n,a[103][103],dis[103],vis[103];
//数组存储两点之间距离,dis存放的是未加入集合的点到集合中的点的最短距离,vis识别是否加入集合;
int prim()
{
int i,j,k,minx,ans=0;
memset(vis,0,sizeof(vis));
for(i=0;i<n;i++)//第一次复制,其他点到0点的距离;
dis[i]=a[0][i];
vis[0]=1;//0点加入集合;
for(i=1;i<n;i++)//循环n-1次;
{
minx=100001;
for(j=0;j<n;j++)
if(!vis[j]&&dis[j]&&minx>dis[j])//注意dis[j]为零不考虑;
{
minx=dis[j];//未加入集合到集合中的点的最近距离;
k=j;
}
vis[k]=1;//k是到集合中的点的最近点,k加入集合;
ans+=dis[k];
for(j=0;j<n;j++)//计算dis[j],即未加入集合点到集合中j的最近距离;
if(!vis[j]&&dis[j]>a[k][j])
dis[j]=a[k][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;
}
2、kruskal算法
#include <iostream>
#include <algorithm>
using namespace std;
int a[103][103],p[103],ans;
struct node{
int x,y,a;
bool operator <(const node& s)const
{
return a<s.a;
}
}q[5000];
int fin(int x)
{
return p[x]==x?x:fin(p[x]);
}
void join(int n)
{
int f1,f2;
f1=fin(q[n].x);
f2=fin(q[n].y);
if(f1!=f2)
{
p[f1]=f2;//纠结了好久原来是这错了;
ans+=q[n].a;
}
}
int main()
{
int n;
while(cin>>n)
{
ans=0;
int k=0;
for(int i=0;i<n;i++)
p[i]=i;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
cin>>a[i][j];
if(i>j)
{
q[k].x=i;
q[k].y=j;
q[k].a=a[i][j];
k++;
}
}
sort(q,q+k);
for(int i=0;i<k;i++)
join(i);
cout<<ans<<endl;
}
return 0;
}
在给几组测试样例:
输入:
3
0 1 4
1 0 2
4 2 0
6
0 45 86 12 61 51
45 0 80 99 18 2
86 80 0 9 37 14
12 99 9 0 14 90
61 18 37 14 0 52
51 2 14 90 52 0
10
0 1 1 1 1 1 1 1 1 1
1 0 1 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1 1 1
1 1 1 0 1 1 1 1 1 1
1 1 1 1 0 1 1 1 1 1
1 1 1 1 1 0 1 1 1 1
1 1 1 1 1 1 0 1 1 1
1 1 1 1 1 1 1 0 1 1
1 1 1 1 1 1 1 1 0 1
1 1 1 1 1 1 1 1 1 0
10
0 40613 19297 99549 27948 50416 95139 82856 99082 79380
40613 0 96888 46784 65549 8396 18128 31348 94809 16773
19297 96888 0 83011 20456 42383 34635 86957 85569 95179
99549 46784 83011 0 24003 66861 44068 11524 97968 22654
27948 65549 20456 24003 0 16590 54758 37348 62125 17814
50416 8396 42383 66861 16590 0 67234 14142 90848 64960
95139 18128 34635 44068 54758 67234 0 81632 81223 19101
82856 31348 86957 11524 37348 14142 81632 0 38508 16462
99082 94809 85569 97968 62125 90848 81223 38508 0 37607
79380 16773 95179 22654 17814 64960 19101 16462 37607 0
输出:
3
51
9
162602