最小產生樹——prim演算法實現_演算法

來源:互聯網
上載者:User

#include <iostream>
#include <stdlib.h>
#include<string>
#include<vector>
#define  max_vex  6

typedef  struct{
 string  s;
 int  lowcast;
 }mm;
 
 string  ss[max_vex]={"v1","v2","v3","v4","v5","v6"};
 
  mm  closedge[max_vex];
  mm arcs[max_vex][max_vex];
  vector<string> G(ss,ss+max_vex); //////初始化
  vector<string>  U;  //用於記錄依次添加的結點
 
 
 int  locatevex(vector<string> G,string u)
   {
   
        int iter1=0;
            while(iter1<G.size())
           {
             if(u==G[iter1]) return  iter1;
               ++iter1;
            }
           
   }
 
 
 
    int  minimum(mm *closedge)
  {
   int min=32;
   int p;
   for(int i=0;i<max_vex;i++)
    if(min>closedge[i].lowcast &&closedge[i].s!="NULL") {p=i; min=closedge[i].lowcast;}
    return  p;
  }
 
 

int main(int argc, char *argv[])
{
  int sum=0;
  string u;
 
   int i,j;
  
   cout<<"請輸入CARS初始用數組:"<<endl;
   for(i=0;i<max_vex;i++)
     for(j=0;j<max_vex;j++)
       cin>>arcs[i][j].s>>arcs[i][j].lowcast;
      
       u="v1";
       cout<<u;  ////確定第一個結點
       cout<<endl;
     
        int k=locatevex(G,u);
        
         for(j=0;j<G.size();j++)
            if(j!=k)   {closedge[j].s=u; closedge[j].lowcast=arcs[k][j].lowcast;}  ////輔助數組的初始化
        
         closedge[k].lowcast=0;  
         closedge[k].s="NULL";
         U.push_back(u);  //////將第一個結點加入向量U中
   
     for(i=1;i<G.size();i++)
       {
         k=minimum(closedge);  /////找一個最短邊的下標
      
         cout<<closedge[k].lowcast;
         cout<<G[k];
         cout<<endl;
     
          sum+=closedge[k].lowcast; ///加兩結點間的路徑和
         U.push_back(G[k]);
 
         closedge[k].lowcast=0;
         closedge[k].s="NULL";
        for(j=0;j<G.size();j++)
          if(arcs[k][j].lowcast<closedge[j].lowcast)
             {
              closedge[j].lowcast=arcs[k][j].lowcast;
               closedge[j].s=G[k];
              }
       }
       cout<<endl;
      
      for(i=0;i<U.size();i++)
       cout<<U[i]<<"  ";
      
       cout<<"輸出最小路徑為:"<<endl;
       cout<<sum<<endl;
  system("PAUSE"); 
  return 0;
}

最近也許是因為整天在上演算法分析,自己的興趣也隨著上課只增不減了,其實最小產生樹早在大二一期就學了的。只是因為當時看到那書上的演算法就暈,看不懂它是什麼意思,也許最主要是自己沒下功夫,也沒到很冷靜地去想那問題了,一直到現在,上節課老師也只是講了思路,但總感覺自己會想應該就能編吧,下午家教回來本來想早點休息的,但無意看到了資料結構的書,就想到還有上節課的自己還想了一下子的最小產生演算法,慢慢編下來,感覺還不錯,終於明白很多事情只要開始了,還真的不難,雖然今天沒做什麼,這個題目也沒什麼難度感,但也讓我更加體會到容器的使用,看來它們還真是個好東西。儘管沒什麼特大價值,但這個小問題也提升了自己的小小滿足感。以後應該會耐心多了。還有很多任務等著呢。慢慢加油咯。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.