https://en.wikipedia.org/wiki/Prim%27s_algorithm
1 int n,m; 2 struct edgetype 3 { 4 int from; 5 int to; 6 int len; 7 }; 8 struct pointtype 9 { 10 vector<edgetype> next; 11 bool vis; 12 }point[100001]; 13 struct com 14 { 15 bool operator ()(edgetype& x,edgetype& y) 16 { 17 return x.len>y.len; 18 } 19 }; 20 priority_queue<edgetype,vector<edgetype>,com> heap; 21 void init() 22 { 23 scanf("%d%d",&n,&m); 24 for(int i=1;i<=n;i++) 25 { 26 point[i].next.clear(); 27 point[i].vis=false; 28 } 29 for(int i=1;i<=m;i++) 30 { 31 edgetype tmp; 32 scanf("%d%d%d",&tmp.from,&tmp.to,&tmp.len); 33 point[tmp.from].next.push_back(tmp); 34 swap(tmp.from,tmp.to); 35 point[tmp.from].next.push_back(tmp); 36 } 37 vector<edgetype>::iterator it; 38 for(it=point[1].next.begin();it!=point[1].next.end();it++) 39 { 40 heap.push(*it); 41 } 42 point[1].vis=true; 43 return; 44 } 45 int prim() 46 { 47 int res=0; 48 while(!heap.empty()) 49 { 50 edgetype now=heap.top(); 51 heap.pop(); 52 int tip=now.to; 53 if(!point[tip].vis) 54 { 55 point[tip].vis=true; 56 res+=now.len; 57 vector<edgetype>::iterator it; 58 for(it=point[tip].next.begin();it!=point[tip].next.end();it++) 59 { 60 if(!point[(*it).to].vis) 61 { 62 heap.push(*it); 63 } 64 } 65 } 66 } 67 return res; 68 }