prim算法——小根堆实现

来源:互联网 发布:手机淘宝网登录在哪里 编辑:程序博客网 时间:2024/06/06 12:38
#include <iostream>#include <queue>#include <vector>using namespace std;typedef pair<int,int> p;const int max_n=1000;const int inf=(1<<30);vector<p> m[max_n];bool used[max_n];int v,e;int prim(){priority_queue<p,vector<p>,greater<p> > q;q.push(p(0,1));int res=0,num=0;while(!q.empty()){p t=q.top();q.pop();num++;res+=t.first;int v=t.second;used[v]=1;for(int i=0;i<m[v].size();i++){p temp=m[v][i];if(!used[temp.second]) q.push(temp); }while(!q.empty()&&used[q.top().second]) q.pop();}if(num==v) return res;else return -1;// 表示是一个非连通图 }int main(){int from,to,c;while(cin>>v>>e,~v){for(int i=0;i<v+1;i++){m[i].clear();used[i]=false;}while(e--){cin>>from>>to>>c;m[from].push_back(p(c,to));m[to].push_back(p(c,from));}cout<<prim()<<endl;}return 0;}/*测试范例:7 9   //结点数和边数1 2 12 3 22 4 33 5 102 7 74 7 14 6 55 7 56 7 8*/


原创粉丝点击