The minimum spanning tree algorithm greedy

// Program 2-6 
#include <the iostream> the using namespace STD; const int INF = 0x3FFFFFFF ;
 const int N = 100 ;
 BOOL S [N];
 int Closest [N];
 int Lowcost [N];
 void Prim ( int n- , int u0, int C [N] [N]) 
{     // vertex number n, starting vertex u0, weighted adjacency matrix C [n-] [n-]
     // if s [i] = true, vertex i has been described Add minimum spanning tree
     // vertex set U; otherwise, the VU vertex i belong to the set
     // pass the final value of the minimum weight associated array Lowcost 
    S [U0] = to true
 

  ; // initially set U only one element, i.e. the apex U0 
    int I;
     int J;
     for (I = . 1 ; I <= n-; I ++ ) 
    { 
        IF (! I = U0) 
        { 
            Lowcost [I] = C [U0] [I]; 
            Closest [I] = U0; 
            S [I] = to false ; 
        } 
        the else 
            Lowcost [I] = 0 ; 
    } 

    for (I = . 1 ; I <= n-; I ++) // in the collection Vu Looking from the latest set of vertices U T 
    {
         int TEMP =INF;
         int T = U0;
         for (J = . 1 ; J <= n-; J ++ ) 
        { 
            IF ((S [J]) && (Lowcost [J] <! TEMP)) 
            { 
                T = J; 
                TEMP = Lowcost [J ]; 
            } 
        } 
        IF (t == U0)
             BREAK ;        // can not find t, out of the loop 

        S [t] = to true ;      // otherwise, t is added stresses set the U- 
        for (J = . 1 ; J <= n-; J ++ ) // update lowcost and closest
        {
            if((!s[j])&&(c[t][j]<lowcost[j]))
            {
                lowcost[j]=c[t][j];
                closest[j]=t;
            }
        }
    }
}

int main()
{

        int n, c[N][N], m, u, v, w;
        int u0;
        cout<<"输入结点数n和边数m:"<<endl;
        cin>>n>>m;
        int sumcost=0;
        for(int i=1; I <= n-; I ++ )
             for ( int J = . 1 ; J <= n-; J ++ ) 
                C [I] [J] = INF; 
        COUT << " Enter the number of nodes u, v, and boundary W: " << endl;
         for ( int I = . 1 ; I <= m; I ++ ) 
        { 
            CIN >> >> U V >> W; 
            C [U] [V] = C [V] [U] = W; 
        } 
        COUT << " enter any node U0: " << endl; 
        CIN >>u0;
        // sum calculating final lowcos, namely the final required minimum sum of costs 
        Prim (n-, U0, C); 
        COUT << " the contents of the array lowcost " << endl;
         for ( int I = . 1 ; I <= n-; I ++ ) 
            COUT << Lowcost [I] << "  " ; 
        COUT << endl;
         for ( int I = . 1 ; I <= n-; I ++ ) 
           sumcost + = [I] Lowcost; 
        COUT << " minimum the cost is: " << << sumcostendl;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/xjyxp/p/11332496.html