基本思想:
本质上是利用一次稠密图Prim算法解决,不难;
关键点:
无;
#include<iostream> #include<vector> #include<string> #include<algorithm> #include<cmath> using namespace std; const int maxn = 110; const double INF = 1000000000.0; double ma[maxn][maxn]; bool vis[maxn]; double dis[maxn]; struct node{ double x, y; }; vector<node>vec; int n; void init() { fill(dis, dis + maxn, INF); fill(ma[0], ma[0] + maxn * maxn, INF); fill(vis, vis + maxn, false); } double prim() { dis[0] = 0; double ans=0; for (int u = 0; u < n; u++) { int index = -1; double min = INF; for (int i = 0; i < n; i++) { if (!vis[i] && min > dis[i]) { min = dis[i]; index = i; } } if (index == -1) return -1; ans += dis[index]; vis[index] = true; for (int i = 0; i < n; i++) { if (!vis[i] && ma[index][i] != INF && ma[index][i] < dis[i]) { dis[i] = ma[index][i]; } } } return ans; } int main() { while (cin >> n) { double a, b; init(); for (int i = 0; i < n; i++) { cin >> a >> b; node no; no.x = a; no.y = b; vec.push_back(no); for (int i = 0; i < vec.size()-1; i++) { double dis = pow(a - vec[i].x,2) + pow(b - vec[i].y,2); dis = sqrt(dis); ma[i][vec.size() - 1] = ma[vec.size() - 1][i] = dis; } } printf("%.2lf\n", prim()); } return 0; }
原文:https://www.cnblogs.com/songlinxuan/p/12589683.html