一次通过,刚学prim的时候做过一道类似的,将每个点之间的距离保存在double型的邻接矩阵里,然后调用prim
#include <iostream> #include <algorithm> #include <iomanip> #include <cstring> #include <cmath> using namespace std; #ifndef ONLINE_JUDGE #include <fstream> ifstream fin("test.txt"); #define cin fin #endif double graph[110][110]; const int INF = 1000000; double dist(double a, double b, double c, double d) { return sqrt((a-c)*(a-c)+(b-d)*(b-d)); } double prim(int n) { double lowcost[110],sum = 0; bool used[110]; memset(used,0,sizeof(used)); int i,j,k; for(i = 1; i <= n; ++i) lowcost[i] = graph[i][1]; used[1] = 1; for(i = 1; i < n; ++i) { double min = INF; k = 1; for(j = 2; j <= n; ++j) { if(lowcost[j] < min && !used[j]) { k = j; min = lowcost[j]; } } used[k] = 1; sum += lowcost[k]; // sum += min; 搞不懂为什么这么写会错,输出变成了10000003.41 //明白了,输出1000003.41是因为i循环哪里多了一个等号,循环了n次,事实上只用n-1次 for(j = 2; j <= n; ++j) if(graph[k][j] < lowcost[j] && !used[j]) lowcost[j] = graph[k][j]; } return sum; } int main() { ios::sync_with_stdio(false); int n,i,j; double x[110],y[110]; while(cin >> n) { for(i = 1; i <= n; ++i) cin >> x[i] >> y[i]; for(i = 1; i <= n; ++i) for(j = 1; j <= n; ++j) graph[i][j] = dist(x[i],y[i],x[j],y[j]); cout <<fixed << setprecision(2) << prim(n) << endl; } return 0; }