prim 算法加模板
生活随笔
收集整理的這篇文章主要介紹了
prim 算法加模板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最小生成樹的prim算法:
1,在頂點中任取一點,加入集合U中;
2,在集合外的點中找到離集合中的點中最近的點并構成路徑,找到的點加入集合中;
3,重復2過程到樹構建完畢;
舉個栗子:
從1開始,1加入集合U中,2,3,4,在集合外;
選擇離集合中點最近的點4,4加入集合中,2,3在集合外;
選擇離集合中點最近的點2,2加入集合中,3在集合外;
選擇離集合中點最近的點3,3加入集合中,完畢;
測試:
代碼:
#include<iostream> #include<cstring> #include<climits> using namespace std; const int M=500; int cost[M][M]; int Creat(){int n,m;cin>>n>>m;for(int q=1;q<=n;q++){for(int w=1;w<=n;w++)cost[q][w]=INT_MAX;}int a,b,c;for(int q=1;q<=m;q++){cin>>a>>b>>c;cost[a][b]=c;cost[b][a]=c;}return n; } void prim(int n){int close[M],lowcost[M];for(int q=1;q<=n;q++){close[q]=1;lowcost[q]=cost[1][q];}close[1]=-1;for(int q=1;q<n;q++){int Min=INT_MAX,u=q;for(int w=1;w<=n;w++)if(close[w]!=-1 && lowcost[w]<Min){Min=lowcost[w];u=w;}cout<<"("<<close[u]<<","<<u<<")"<<" "<<lowcost[u]<<endl;for(int w=1;w<=n;w++)if(close[w]!=-1 && lowcost[w]>cost[u][w]){lowcost[w]=cost[u][w];close[w]=u;}}return; } int main() {int t;cin>>t;while(t--){int n=Creat();prim(n);}return 0; }
轉載于:https://www.cnblogs.com/zhizhaozhuo/p/9594238.html
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的prim 算法加模板的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 启动php出现的错误
- 下一篇: 用python写网络爬虫 -从零开始 3