今天整理调试的prim算法代码: #include "stdafx.h" #include <limits> #include <iostream> #include <fstream> using namespace std; const int MAXINT = numeric_limits<int>::max(); template <class Type> void Prim(int n, Type** c) { bool *s = new bool[n+1]; int *closest = new int[n+1]; Type * lowcast = new Type[n+1]; int i, j, k; s[1] = true; for(i = 2; i <= n; i++) { s[i] = false; closest[i] = 1; lowcast[i] = c[1][i]; } for(i = 1; i < n; i++) { Type min = static_cast<Type>(MAXINT); j = 1; for(k = 2; k <=n ; k++) { if(lowcast[k] < min &&(!s[k])) { min = lowcast[k]; j = k; } } cout << j <<"-" << closest[j] <<endl; s[j] =true; for(k = 2; k <=n ; k++) { if((!s[k])&&c[j][k]<lowcast[k]) { lowcast[k] = c[j][k]; closest[k] = j; } } } delete [] s; delete [] closest; delete [] lowcast; } int _tmain(int argc, _TCHAR* argv[]) { int prev[6], dist[6]; int i,j,n; int** myc; FILE *fp; fp=fopen("data.txt", "r"); fscanf(fp,"%d", &n); myc = new int* [n+1]; for(i =0; i<=n; i++) myc[i] = new int[n+1]; for(i=1; i<=n; i++) for(j =1; j<=n; j++) { fscanf(fp, "%d",&myc[i][j]); if (myc[i][j]==-1) myc[i][j] = MAXINT; } Prim(5, myc); for(i = 0; i<=5; i++) delete[] myc[i]; delete [] myc; return 0; } 数据文件data.txt格式如下: 5 0 10 -1 30 100 10 0 50 -1 -1 -1 50 0 20 10 30 -1 20 0 60 100 -1 10 60 0