Two algorithms for minimum spanning tree: prim and Kruskal algorithms

Source: Internet
Author: User

More and more understand a reason: you can not write code for only one reason, that is, you do not thoroughly understand the idea of the algorithm!!

Previously wrote the minimum spanning tree, but, after a few problems, after a period of time, will forget, a little can not write out. Maybe there's only one reason why I don't have a thorough understanding of the two algorithms.

Theme:

In fact, the minimum spanning tree has two points, one is the least weight, and the other is that the graph must be a tree. The difference between prim and Kruskal is that the variables chosen are different, and prim choose to always keep the weights to a minimum, and then build a tree on a dot-by-point basis. And Kruskal is always guaranteed to be a tree (although the construction process is not necessarily a real tree, but also check the set of the ring can be understood as follows: is to ensure that the result is a tree), and then add the edge, so that the weight of the smallest.

Knowing both of these ideas, come to talk about the code (all based on greed) implementation:

Prim: (Here the weights are understood as a distance) hypothesis, the set of points has been determined to be S, then the indeterminate point can be recorded as 1-s, we each time from a set of 1-s points not determined, select a place in the set S point directly connected, and the weight of the smallest (greedy) points into s, may be this point is T, Then S and 1-s will change: since T becomes a point in S, the distance of the point connected to T in 1-s actually becomes the distance between that point and S. Since there is already a point already marked in the initialization, it is sufficient to loop N-1 times, and only N-1 times, otherwise errors may occur (depending on the INF), which is the prim algorithm.


Kruskal: This algorithm relative to prim is better understanding, each time the right value of the smallest (greedy) side, and then see whether the two points of the edge of the tree contradiction (with and check set judgment on the line), in the process of adding edge record the number of effective points, to reach the end of N, do not have to take into account every side.


Attached: HDU 1233 is also the code of two algorithms for smooth engineering, which helps to understand:


Prime:

#include <iostream> #include <cstdio> #include <cstring> #include <queue> #define INF    0x7fffffffusing namespace Std;int map[110][110],dis[110],vis[110];int n,m;void prime () {memset (VIS); The for (int i=1;i<=n;i++) dis[i]=map[1][i];//weights can be understood as distances, and it seems better to understand the initial 1 of the int sum=0;vis[1]=1;//as the starting point, which can be any point for (int p=1;p<=n        -1;p++) {//For N-1 cycles, add the remaining N-1 points int t,min=inf;        for (int i=1;i<=n;i++) if (!vis[i] && dis[i]<min)//Find early set 1-s to the nearest point T min=dis[i],t=i of the set S;        Sum+=min;vis[t]=1;    for (int i=1;i<=n;i++) if (!vis[i] && dis[i]>map[t][i])//update the distance from the point in the 1-s to the set S of the t connected to the dis[i]=map[t][i]; } Cout<<sum<<endl;}    int main () {//freopen ("D:\\in.txt", "R", stdin);        while (Cin>>n && N) {for (Int. i=0;i<=n;i++) for (int j=0;j<=n;j++) Map[i][j]=inf;        M= (N-1) *N/2;        int a,b,c;            for (int i=0;i<m;i++) {scanf ("%d%d%d", &a,&b,&c); map[a][B]=map[b][a]=c;    } prime (); } return 0;}


Kruskal:


#include <iostream> #include <cstdio> #include <algorithm>using namespace std;struct edge{    int u, V,w;    BOOL operator< (const edge &a) const{        return w<a.w;    }} E[10010];int n,m;int pre[110];int Find (int x) {    int t=x;    while (pre[t]!=t) t=pre[t];    while (x!=t) pre[x]=t,x=pre[x];    return t;} void Kruskal () {for    (int i=0;i<=n;i++) pre[i]=i;//initial session and check set    int cnt=1,ans=0;    for (int i=0;i<m;i++) {        int u=e[i].u,v=e[i].v,w=e[i].w;        int Fu=find (U), Fv=find (v);        if (FU==FV) continue;//and check the set to determine whether the nature of the tree satisfies the        ans+=w;        pre[fv]=fu;cnt++;        if (cnt==n) break;//is already full tree    }    cout<<ans<<endl;} int main () {    //freopen ("D:\\in.txt", "R", stdin);    while (Cin>>n && N) {        m=n* (N-1)/2;        for (int i=0;i<m;i++) {            scanf ("%d%d%d", &E[I].U,&E[I].V,&E[I].W);        }        Sort (e,e+m);//Sort the edges        Kruskal ();    }    return 0;}


Two algorithms for minimum spanning tree: prim and Kruskal algorithms

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.