Basic ideas:
Defines the set of nodes U, V (U indicates that a set of nodes has been selected to join the MST, V indicates that it is not selected)
1. Optional one node join U
2. Select a side with the smallest edge, and his two nodes belong to U, V, and add the node that belongs to V to u
3. Repeat execution 2 until v empty
Pseudo Code:
C + + code:
int G[MNX][MNX];
int n, m;
int D[MNX];
Plain Prim, complex O (| V|^2) | v|: Points, | e|: Number of edges
int prim () {
memset (d, 0x3f, sizeof D);//Initialize
int ret = d[1] = 0; First the d[1] into 0 for
(int i = 1; I <= n; ++i) {
int u =-1;
for (int j = 1; j <= N; ++j) //Find d[u] the smallest u
if ((U = 1 | | d[u] > D[J]) && D[j]!=-1)
u = j;< C16/>ret + = D[u];
D[u] =-1;
for (int j = 1; j <= N; ++j) /Update and U adjacency node D[j] Value
d[j] = min (d[j), g[u][j]);
return ret;
}
Algorithm Analysis:
The main cost is to find the edge of the smallest edge, this step of the double cycle cost θ (N2), so the algorithm time complexity of θ (N2).
Heap Optimization Improvements:
We use a small top heap to find the smallest edge, like the Dijkstra algorithm, the algorithm has a total of n-1 insertion, n-1 Delete, m-n+1 secondary siftup operation. The total time complexity is O (MLOGN).
Pseudo Code:
C + + code:
int FST[MNX], nxt[mxe], Cost[mxe], To[mxe], E;
void Init () {
memset (FST,-1, sizeof FST);
e = 0;
}
void Add (int u, int v, int c) {
To[e] = V, nxt[e] = Fst[u], cost[e] = c, fst[u] = e++;
}
struct Node {
int u, dis;
node (int u, int dis): U (u), dis (dis) {}
bool operator < (const node &b) const {return
dis > B.DIS;
}
};
Heap optimization, Complexity O (| E|log| v|), dense graphs are comparatively slow
int primheap () {
memset (d, 0x3f, sizeof D);
D[1] = 0;
priority_queue<node> Q;
Q.push (Node (1,0)); First node is selected
int ret = 0;
while (!q.empty ()) {
int u = q.top (). u;
int dd = q.top (). Dis;
Q.pop ();
if (D[u]!= dd) continue; If the value is updated before the words are not taken, continue off
ret + dd;
D[u] =-1;
for (int j = Fst[u]; ~j j = nxt[j]) {
int v = to[j], c = cost[j];//Update
if (D[v] > C && d[v]!=-1) C31/>D[V] = C;
Q.push (Node (v, c));
}} return ret;
}