链接三维空间中n个点的最短距离 最小生成树(krukal算法)
2016-07-23 19:21
429 查看
DESCRIPTION
Spoon Devil build a 3-D matrix, and he(orshe) wants to know if he builds some bases what's the shortest distance toconnect all of them.
INPUT
There are multiple test cases. The firstline of input contains an integer T, indicating the number of test cases. Foreach test case:
The first line contains one integern (0<n<50), indicating the number of all points. Then the next nlines, each lines contains three numbers xi,yi,zi indicating the position ofi-th point.
OUTPUT
For each test case, output a line, whichshould 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
题意
求连n个点(三维坐标),所需要的最短距离。(最小生成树)
1.首先对点做预处理2.用krukal算法进行求解。
Spoon Devil build a 3-D matrix, and he(orshe) wants to know if he builds some bases what's the shortest distance toconnect all of them.
INPUT
There are multiple test cases. The firstline of input contains an integer T, indicating the number of test cases. Foreach test case:
The first line contains one integern (0<n<50), indicating the number of all points. Then the next nlines, each lines contains three numbers xi,yi,zi indicating the position ofi-th point.
OUTPUT
For each test case, output a line, whichshould 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
题意
求连n个点(三维坐标),所需要的最短距离。(最小生成树)
1.首先对点做预处理2.用krukal算法进行求解。
#include <stdio.h> #include <string.h> #include <math.h> int n,m; double s; int p[1005]; struct ed{ int u; int v; double w; }; struct asd{ int x; int y; int z; }; struct ed e[5000]; int find (int x) { return p[x]==x?x:p[x]=find(p[x]); } void kru() { int i,j,x,y; for(i=1;i<=m;i++) { x=find(e[i].u); y=find(e[i].v); if(x!=y) { p[x]=y; s=s+e[i].w; } } } void sort() { int i,j,k; struct ed t; for(i=1;i<=m-1;i++) { k=i; for(j=i+1;j<=m;j++) if(e[j].w<e[k].w) k=j; t=e[k]; e[k]=e[i]; e[i]=t; } } int main() { int T; scanf("%d",&T); while(T--) { s=0; scanf("%d",&n); int i,j,x,y,z,k; m=(n*(n-1))/2; asd b[51]; for(i=1;i<=n;i++) { scanf("%d %d %d",&b[i].x,&b[i].y,&b[i].z); } k=1; for(i=1;i<n;i++) { for(j=i+1;j<=n;j++) { e[k].w=sqrt((b[i].x-b[j].x)*(b[i].x-b[j].x)+(b[i].y-b[j].y)*(b[i].y-b[j].y)+(b[i].z-b[j].z)*(b[i].z-b[j].z)); e[k].u=i; e[k].v=j; k++; } } for(i=1;i<=n;i++) p[i]=i; sort(); kru(); printf("%.2f\n",s); } }
相关文章推荐
- android studio tabhost基础 多功能时钟app 实现时钟功能
- Java面向对象的三个基本特征:封装、继承、多态
- mysql cluster
- java bean对象转换json对象时过滤空值
- 深入解析MySQL分区(Partition)功能
- java 读取文件
- CodeForces - 560A Currency System in Geraldion
- 支配集、覆盖集、独立集与匹配
- java-并发-ConcurrentHashMap高并发机制-jdk1.8
- POJ1328-Radar Installation(贪心)
- C++基础:文件与对象
- 对最小二乘法的概率解释.
- Git用户手册--Git 内部原理
- HDU 1598 find the most comfortable road
- HDU - 5319 Painter
- 单链表的建立
- Android Retrofit使用(一)
- java中对列表的添加或删除操作
- 实现QQ空间中显示照片效果
- C++基础:文件读写