您的位置:首页 > 其它

1002 ProblemB

2016-06-20 10:57 405 查看
题意:

给出点的坐标求连通所有的点画的最短线,结果保留两位小数。

思路:

知道坐标就可以求出两点间距离,然后用最小生成树做。

// problemB.cpp : 定义控制台应用程序的入口点。
//

//#include "stdafx.h"
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iomanip>
using namespace std;
double path[102][102];
int flag[102];
double closedge[102];
double ma;
double cnt;

typedef struct {
double x, y;
}input;

input temp[102];

double calculate(double x1, double y1, double x2, double y2)
{
return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}

double CreatMST(int n)
{
int i, j, x;
double k;
flag[0] = 1;
for (i = 1; i<n; ++i)
closedge[i] = path[0][i];
for (i = 1; i<n; ++i)
{
k = ma, x = 1;
for (j = 1; j<n; ++j)
if (!flag[j] && closedge[j] < k)
x = j, k = closedge[j];
flag[x] = 1;
cnt += k;
for (j = 1; j<n; ++j)
if (!flag[j] && closedge[j] > path[x][j])
closedge[j] = path[x][j];
}
return cnt;
}

int main()
{
int i, j, k, t, x, y, n, m;
while (cin>>n)
{
ma = 0;
cnt = 0;
memset(temp, 0, sizeof(input) * 102);
memset(flag, 0, sizeof(flag));
memset(closedge, 0, sizeof(closedge));
memset(path, 0, sizeof(double) * 102 * 102);
for (i = 0; i<n; ++i)
cin>>temp[i].x>>temp[i].y;

for (i = 0; i<n; ++i)
for (j = 0; j<n; ++j)
{
path[i][j] = calculate(temp[i].x, temp[i].y, temp[j].x, temp[j].y);
if (ma < path[i][j]) ma = path[i][j];
}
cout << setiosflags(ios::fixed) << setprecision(2) << CreatMST(n) << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: