YTU 1012: A MST Problem
1012: A MST Problem
时间限制: 1 Sec 内存限制: 32 MB提交: 7 解决: 4
题目描述
It is just a mining spanning tree ( 最小生成树 ) problem, what makes you a little difficult is that you are in a 3D space.
输入
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.
输出
For each test case, output a line with the answer, which should accurately rounded to two decimals .
样例输入
2
2
1 1 0
2 2 0
3
1 2 3
0 0 0
1 1 1
样例输出
1.41
3.97
你 离 开 了 , 我 的 世 界 里 只 剩 下 雨 。 。 。
#include<iostream> #include<cmath> #include<cstdio> #include<cstring> using namespace std; const int infinity=99999999; const int maxnum=105; double map1[maxnum][maxnum]; bool visited[maxnum]; double low[maxnum]; int nodenum; struct node { int x; int y; int z; } nd[105]; double prim() { int i,j,pos=1; double result,Min; memset(visited,0,sizeof(visited));//初始化都未标记 result=0; for(i=1; i<=nodenum; i++) low[i]=map1[pos][i]; visited[pos]=1;//把1号作为起点 for(i=2; i<=nodenum; i++) //这个i没有其他的意思就是一个循环次数 { Min=infinity; pos=-1;//从1号开始找最小的边 for(j=1; j<=nodenum; j++) if(!visited[j]&&Min>low[j]) { Min=low[j]; pos=j; } if(pos==-1) return -1; visited[pos]=1;//做到与1os号最近的边 result+=Min;//加权值 for(j=1; j<=nodenum; j++) if(!visited[j]&&low[j]>map1[pos][j]) low[j]=map1[pos][j];//这个就是替换未被标记的最小权值! } return result; } int main() { int n,i,j,t; double lenth,ans; cin>>t; while(t--) { cin>>n; nodenum=n; for(i=1; i<=nodenum; i++) for(j=1; j<=nodenum; j++) map1[i][j]=infinity; for(i=1; i<=n; i++) cin>>nd[i].x>>nd[i].y>>nd[i].z; for(i=1; i<=n; i++) { for(j=i+1; j<=n; j++) { lenth=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)); // printf("djklsajiofgioj%.2lf\n",lenth); map1[i][j]=map1[j][i]=lenth; } } ans=prim();//开始rim算法 if(ans==-1) cout<<"?"<<endl; else printf("%.2lf\n",ans); } }
------------------- 这是千千的个人网站哦! https://www.dreamwings.cn -------------------