不知道怎么评价题目,出题人把一个简单的问题搞得不伦不类…
其实非常简单,用prim算法求最小生成树即可。
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cmath>
using namespace std;
const int MAXN = 5010;
struct Point {
int x;
int y;
}point[MAXN];
double ans, dis[MAXN];
bool vis[MAXN];
int n;
double distance(int a, int b) {
return sqrt((double)(point[a].x - point[b].x) * (point[a].x - point[b].x) + (double)(point[a].y - point[b].y) * (point[a].y - point[b].y));
}
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> point[i].x >> point[i].y;
dis[i] = 1e8;
}
int pos; dis[1] = 0;
for (int i = 1; i <= n; ++i) {
double minn = 1e8;
for (int j = 1; j <= n; ++j)
if (!vis[j] && dis[j] < minn) {
minn = dis[j]; pos = j;
}
ans += minn; vis[pos] = true;
for (int j = 1; j <= n; ++j) {
double d = distance(pos, j);
if (d < dis[j]) dis[j] = d;
}
}
cout << fixed << setprecision(2) << ans;
return 0;
}