1012: A MST Problem
Time Limit: 1 Sec Memory Limit: 32 MBSubmit: 18 Solved: 13
[ Submit][ Status][ Web Board]
Description
It is just a mining spanning tree ( 最小生成树 ) problem, what makes you a little difficult is that you are in a 3D space.
Input
The first line of the input contains the number of test cases in the file. And t he first line of each case
contains one integer numbers n(0<n<30) specifying the number of the point . The n next n line s, each line
contain s Three Integer Numbers xi,yi and zi, indicating the position of point i.
Output
For each test case, output a line with the answer, which should accurately rounded to two decimals .
Sample Input
2
2
1 1 0
2 2 0
3
1 2 3
0 0 0
1 1 1
Sample Output
1.41
3.97
import java.util.*;
public class AMSProblem{
static int n,m;
static int inint=9999999;
static double[][] map=new double[101][101]; //记录两个顶点间的距离
static int[] visited=new int[31]; //判断该顶点是否被访问过
static double[] min=new double[31]; //记录与每个节点相连的所有路径长度
public static double prim() {
int p=0;
double minl,result = 0; //result为最后的最短路径长度,minl为中间变量,用来记录最短路径
//初始化visited
for(int i=0;i<m;i++)
visited[i]=0;
//给定最短路径一个初始值,这个初始值是与1相连的所有路径
for(int i=0;i<m;i++)
min[i]=map[p][i];
//将节点1标记为已访问过的节点
visited[p]=1;
for(int i=1;i<m;i++) {
minl=inint;
p=-1;
for(int j=0;j<m;j++) {
//如果该节点未被访问并且路径长度比最短路径小,修改最短路径,记录该点,下一次循环时从该点开始查找
if(visited[j]==0&&min[j]<minl) {
minl=min[j];
p=j;
}
}
if(p==-1)
return -1;
visited[p]=1;
result+=minl;
//记录与此时节点相连的所有路径
for(int j=0;j<m;j++) {
if(visited[j]==0&&min[j]>map[p][j])
min[j]=map[p][j];
}
}
return result;
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
double len,f;
node[] nd=new node[31];
int[][] a=new int[31][31];
String[] s=new String[4];
n=in.nextInt();
while(n!=0) {
m=in.nextInt();
s=in.nextLine().split(" ");
for(int i=0;i<m;i++) {
s=in.nextLine().split(" ");
for(int j=0;j<s.length;j++) {
a[i][j]=Integer.parseInt(s[j]);
}
nd[i]=new node(); //初始化必须做
nd[i].x=a[i][0];
nd[i].y=a[i][1];
nd[i].z=a[i][2];
}
//初始化map
for(int i=0;i<m;i++) {
for(int j=0;j<m;j++) {
map[i][j]=inint;
}
}
//计算每个路径长度
for(int i=0;i<m;i++) {
for(int j=i+1;j<m;j++) {
len=Math.sqrt((nd[i].x-nd[j].x)*(nd[i].x-nd[j].x)+(nd[i].y-nd[j].y)*(nd[i].y-nd[j].y)+
(nd[i].z-nd[j].z)*(nd[i].z-nd[j].z));
map[i][j]=map[j][i]=len;
}
}
f=prim();
System.out.printf("%.2f\n",f);
n--;
}
}
}
class node{
int x;
int y;
int z;
}