The third elastic Ps:prim algorithm of the minimum spanning tree

Source: Internet
Author: User

The basic idea of prim algorithm:

Starting from a vertex U0 in the Connected network n={v,e}, select the Edge (U0,V) with which it is associated with a minimum weight, and add its vertices to the vertex collection U of the spanning tree. Each subsequent step is from one vertex in U, and the other vertex does not select the least-weighted edge (u,v) in each edge of the U, and adds its vertices to the set U. This continues until all vertices in the net are added to the spanning tree vertex collection U.

Because it is similar to Dijkstra, it is stored by adjacency matrix;

Template (Low IQ I determined to take him a name = =)

for (i = 1; I <= n; i++)

for (j = 1; J <= N; j + +)

CIN >> G[i][j];

memset (MINN,0X7F,SIZEOF (Minn)); Initialized to maxint minn[1] = 0;

memset (u,1,sizeof (U)); Initialize to True to indicate that all vertices are blue dots

for (i = 1; I <= n; i++)

{int k = 0; for (j = 1; J <= N; j + +)//Find a blue dot with the smallest weight associated with the white point K

if (U[j] && (Minn[j] < minn[k]))

K = J;

U[k] = false; Blue dot K join spanning tree, mark as white point

for (j = 1; J <= N; j + +)//modify all blue dots connected to K

if (U[j] && (G[k][j] < minn[j])) minn[j] = G[k][j]; }

int total = 0;

for (i = 1; I <= n; i++)//Additive weights

Total + = Minn[i];

cout << Total << Endl;

return 0; }

The third elastic Ps:prim algorithm of the minimum spanning tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.