Add a vis Array Based on the template of my minimum spanning tree Prim algorithm to identify whether a node has been added to set T. Here, the min_dis of a node cannot be used as whether to add the node to T. Because the connected edge is given in the question and its weight is set to 0, an array must be added for determination.
Another note is that here Prim does not necessarily need to execute loop N-1 times, also because Edge permission Initialization is 0. Terminating the cycle in time can slightly improve the efficiency.
My problem-solving code is as follows:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <string> #include <algorithm> using namespace std; #define Distance double #define INF 1000000 #define MAXN 750 double x[MAXN],y[MAXN]; Distance dis[MAXN][MAXN]; Distance min_dis[MAXN]; //int nearest_v[MAXN]; int vis[MAXN]; Distance Prim(int v0, int N) { //init for(int i=0; i<N; i++) { min_dis[i] = dis[i][v0]; // nearest_v[i] = v0; } min_dis[v0] = 0; memset(vis,0,sizeof(vis)); vis[v0] = 1; Distance total_dis = 0; for(int k=1; k<N; k++) { Distance md = INF; int nv = v0; for(int i=0; i<N; i++) if(!vis[i]) { if(md > min_dis[i]) { md = min_dis[i]; nv = i; } } total_dis += md; min_dis[nv] = 0; vis[nv] = 1; for(int i=0; i<N; i++) if(!vis[i]) { if(min_dis[i] > dis[i][nv]) { min_dis[i] = dis[i][nv]; // nearest_v[i] = nv; } } int ok = 0; for(int i=0; i<N; i++) if(min_dis[i]!=0) { ok=1; break; } if(!ok) break; } return total_dis; } int main() { int N,M; while(cin >> N) { for(int i=0; i<N; i++) { scanf("%lf %lf",&x[i],&y[i]); for(int j=0; j<=i; j++) dis[i][j]=dis[j][i]=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])); } cin >> M; int na,nb; for(int i=0; i<M; i++) { scanf("%d %d",&na,&nb); dis[na-1][nb-1]=dis[nb-1][na-1]=0; } printf("%.2lf\n", Prim(0,N)); } return 0; }