Test instructions: N Farms, it takes the shortest distance to connect all the farms together.
Idea: Prim algorithm
Textbook Code:
Prim algorithm #include<iostream> #include <stdio.h> #include <cstring>using namespace std;int n;int tot; int V[150][150];int dist[150];//The minimum distance from the memory node to the tree bool use[150];//tag node whether there is an int main () {while (scanf ("%d", &n)!=eof) {memset (use,false,sizeof (use));//initialization node exists Tot=0;use[0]=1;int i,j,k;for (i=0;i<n;i++) for (j=0;j<n;j++) scanf ("%d", &V[I][J]);d ist[0]=0x7fffffff;//assigned to maximum for (i=1;i<n;i++)//initial distance dist[i]=v[0][i];for (i=1;i<n;i++) {//connection remaining n-1 node int tmp=0;for (k=1;k<n;k++)//Find the shortest distance node if (dist[k]<dist[tmp] &&!use[k]) Tmp=k;tot +=dist[tmp];// Add to total distance use[tmp]=true;for (k=1;k<n;k++)//adjust distance if (!use[k]) dist[k]=v[k][tmp]<dist[k]?v[k][tmp]:d ist[k];} printf ("%d\n", tot);} return 0;}
In addition, the problem can also be used Kruskal algorithm, the code is as follows:
Kruskal algorithm #include<iostream>using namespace std;int fa[120];int get_father (int x) {return fa[x]=fa[x]==x?x:get _father (fa[x]);//Determine whether two nodes belong to a subtree (and check set)}int main () {int n;int p[120][120];int mark[100100];while (scanf ("%d", &n)! = EOF) {memset (mark,0,sizeof (Mark)), int i,j,k,m;for (i=0;i<n;i++) for (j=0;j<n;j++) {scanf ("%d", &p[i][j]); Mark[p[i][j]]=1;} for (i=0;i<n;i++) Fa[i]=i;int ans=0;for (k=1;k<=100000;k++)//Kruskal algorithm if (Mark[k]) {// If no mark is added, timeout for (i=0; i<n;i++) for (int j=0;j<n;j++) if (p[i][j]==k &&get_father (i)!=get_father (j)) {fa[fa[i]]=fa[j];// Merge two subtrees (and look up the set) Ans+=k;}} printf ("%d\n", ans);} return 0;}