一、Description(poj1258)
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
二、问题分析
典型的求最小生成树问题,算法大多用Prim或者Kruskal算法。小弟用了Prim算法,这道题如果掌握了Prim算法,那么问题就迎刃而解了。可惜小弟数据结构学得不怎么踏实,有临时学了一遍,有点蛋疼。
从单一顶点开始,普里姆算法按照以下步骤逐步扩大树中所含顶点的数目,直到遍及连通图的所有顶点。
- 输入:一个加权连通图,其中顶点集合为V,边集合为E;
- 初始化:Vnew = {x},其中x为集合V中的任一节点(起始点),Enew = {};
- 重复下列操作,直到Vnew = V:
- 在集合E中选取权值最小的边(u, v),其中u为集合Vnew中的元素,而v则不是(如果存在有多条满足前述条件即具有相同权值的边,则可任意选取其中之一);
- 将v加入集合Vnew中,将(u, v)加入集合Enew中;
- 输出:使用集合Vnew和Enew来描述所得到的最小生成树。
这里我们改一下算法,是输出的是权值和。
三、Java代码
import java.util.Scanner;
public class Test {
public static int prim(int[][] a, int count) {
int sum = 0;
int i, j, k;
int[] lowcost = new int[count]; //保存相关定点间的权值
int[] adjvex = new int[count]; //保存相关定点的下标
for (i = 0; i < count; i++) {
lowcost[i] = a[0][i];
adjvex[i]=0;
}
for (i = 1; i < count; i++) {
j=0;
while(lowcost[j]==0){
j++;
}
for (k = 1; k < count; k++) {
if ((lowcost[k]!=0) && (lowcost[k] < lowcost[j])) {
j = k;
}
}
sum += lowcost[j];
lowcost[j] = 0;
for (k = 1; k < count; k++) {
if (lowcost[k]!=0 && (a[j][k] < lowcost[k])) {
{
lowcost[k] = a[j][k];
adjvex[k] = j;
}
}
}
}
return sum;
}
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
int n;
while((n=cin.nextInt())!=-1){
int vertexNumber = n;
int arr[][] = new int[vertexNumber][vertexNumber];
for (int i = 0; i < vertexNumber; i++) {
for (int j = 0; j < vertexNumber; j++) {
arr[i][j]=cin.nextInt();
}
}
System.out.println(prim(arr,n));
n=-1;
}
}
}
350



被折叠的 条评论
为什么被折叠?



