Description
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
题目大意:要实现n个农场间网络畅通,现在给出n*n的矩阵。 第i行第j列的数即表示i农场与j农场间的距离。求出实现所有农场网络畅通的最短的总光纤长度。
思路:prim
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAX = 2005;
const int INF = 0x3f3f3f3f;
//最小生成树prim算法
struct A{
int arcs[MAX][MAX];//权值-->字符不同的个数
int arcnum; //边的数目
bool visit[MAX]; //顶点的访问情况
int vexnum; //顶点的数目
}G;
int d[MAX];//选中集与未选中集的距离(记录了最短的路径)
int prim(void){
int min,v,ans=0;
for(int i=0 ; i<G.vexnum ; i++){
d[i] = G.arcs[0][i];
G.visit[i] = false;//每个点未访问
}
//起始点加入选中集
G.visit[0]=true;
for(int i=0 ; i<G.vexnum-1 ; i++){//选n-1个定点
//找出一个最短距离的点
min=INF;
for(int j=0 ; j<G.vexnum ; j++){
if(!G.visit[j] && d[j]<min){
v=j;
min = d[j];
}
}
//已访问
G.visit[v]=true;
ans += min;
//更新选中点集与未选中点集的距离
for(int j=0 ; j<G.vexnum ; j++){
if(!G.visit[j] && G.arcs[v][j]<d[j]){
d[j] = G.arcs[v][j];
}
}
}
return ans;
}
int main(void){
while(cin>>G.vexnum){
//赋权值
for(int i=0 ; i<G.vexnum ; i++){
for(int j=0 ; j<G.vexnum ; j++){
cin>>G.arcs[i][j];
}
}
cout<<prim()<<endl;
}
return 0;
}