The most basic prim algorithm
Let's take a look at Prim's ideas.
Give two arrays
A two-dimensional representation of a graph in the form of an adjacency matrix
A one-dimensional representation of the distance from each node to the current tree
Key See prim function
Because every point is at the end of the tree.
So I first put the first node in (this doesn't matter, whichever you put)
The distance from each node to the tree is then updated (that is, the distance from each point in the adjacency matrix to the first node)
Then I run a For loop
Add the smallest distance to the tree.
And then in a round for loop
To compare the distance between the remaining point and the point to the distance from the remaining point to the original tree.
To update the tree's distance in this way
These two round for loops have a for loop outside
is to add a point to the tree every time.
Finally, all the dots are in the tree.
Of course, there are also Boolean tag arrays to indicate whether a node is already in the tree.
That's not much of the details.
Release code
#include <stdio.h> #include <string.h> #include <iostream> #include <math.h> #include < Algorithm> #define INF 0xffffffusing namespace Std;const int maxn=520;int dis[maxn][maxn];int Dis_tree[maxn];bool Vis [Maxn];int n;int Myfirstprim () {int i,j,v,maxx,minn; Vis[0]=true; for (i=0;i<n;i++) dis_tree[i]=dis[0][i]; maxx=0; for (i=1;i<n;i++) {minn=inf; for (j=0;j<n;j++) {if (Vis[j]==false&&dis_tree[j]<minn) {MINN=DIS_TREE[J]; V=j; }} vis[v]=true; if (Maxx<minn) Maxx=minn; for (j=0;j<n;j++) {if (Vis[j]==false&&dis_tree[j]>dis[v][j]) {D IS_TREE[J]=DIS[V][J]; } } } Return Maxx;} int main () {int t,i,j; scanf ("%d", &t); while (t--) {scanf ("%d", &n); for (i=0;i<n;i++) Vis[i]=false; for (i=0;i<n;i++) for (j=0;j<n;j++) scanf ("%d", &dis[i][j]); printf ("%d\n", Myfirstprim ()); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
POJ 2485:highways