POJ - 2485 Highways

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   div   

題目來源:http://poj.org/problem?id=2485

      用貪心策略構成最小產生樹,有常用的兩種演算法Prim演算法和Kruskal演算法。本題我採用的是Prim演算法。

設帶權圖為V,首先隨便選一點作為構成一個真子集S,然後在採取貪心策略,選取V-S中的某一點到S中

一點的最小距離並將該點添加進去,直到S=V。

 1 #include<stdio.h> 2 const int maxn=500+5; 3 int c[maxn][maxn],lowcost[maxn]; 4 bool s[maxn]; 5 int prime(int n) 6 { 7     s[1]=true; 8     for(int i=2;i<=n;i++){ 9         lowcost[i]=c[1][i];10         s[i]=false;11     }12     int j=1,maxlength=-1;13     for(int i=1;i<n;i++){14         int mincost=65537;15         for(int k=2;k<=n;k++)16             if(mincost>lowcost[k] && !s[k]){17                 mincost=lowcost[k];18                 j=k;19             }20         s[j]=true;21         if(maxlength<mincost)22             maxlength=mincost;23         for(int k=2;k<=n;k++)24             if(c[j][k]<lowcost[k] && !s[k])25                 lowcost[k]=c[j][k];26 27     }28     return maxlength;29 }30 int main()31 {32     int t;33     scanf("%d",&t);34     while(t--){35         int n;36         scanf("%d",&n);37         for(int i=1;i<=n;i++)38             for(int j=1;j<=n;j++)39             scanf("%d",&c[i][j]);40         int ans=prime(n);41         printf("%d\n",ans);42     }43     return 0;44 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.