自己根据《算法导论》伪代码写的c++语言实现prim最小生成树。很烂,但还是发表上来,给自己留个纪念也好
- #include <iostream>
- #include <fstream>
- #include <queue>
- #include <vector>
- #include <algorithm>
- #include <deque>
- #define MAX 100000
- using namespace std;
- int key[100];
- int parent[100];
- int Graphic[100][101];
- int Edge[100][100];
- deque<int> priorityQueue;
- deque<int> primTree;
- int ExtractMin()
- {
- int min=MAX;
- int v,u,r;
- deque<int>::iterator index=priorityQueue.end();
- for(deque<int>::iterator itr=priorityQueue.begin();itr!=priorityQueue.end();itr++)
- {
- v=*itr;
- for(deque<int>::iterator it=primTree.begin();it!=primTree.end();it++)
- {
- u=*it;
- if(Edge[u-1][v-1]!=0&&min>Edge[u-1][v-1])
- {
- index=itr;
- min=Edge[u-1][v-1];
- }
- }
- }
- if(index!=priorityQueue.end())
- {
- r=*index;
- priorityQueue.erase(index);
- primTree.push_back(r);
- }
- else r=-1;
- return r;
- }
- bool Belong(int val)
- {
- if(find(priorityQueue.begin(),priorityQueue.end(),val)!=priorityQueue.end())
- return true;
- else return false;
- }
- void MstPrim(int root,int n)
- {
- for(int i=0;i<n;i++)
- {
- key[i]=MAX;
- parent[i]=0;
- }
- key[root-1]=0;
- int u,v;
- u=root;
- primTree.push_back(root);
- bool flag=true;
- priorityQueue.pop_front();
- while(true)
- {
- if(flag)flag=false;
- else
- u=ExtractMin();
- if(u==-1)break;
- for(int i=1;Graphic[u-1][i]!=0;i++)
- {
- v=Graphic[u-1][i];
- if(Belong(v)&&Edge[u-1][v-1]!=0&&Edge[u-1][v-1]<key[v-1])
- {
- parent[v-1]=u;
- key[v-1]=Edge[u-1][v-1];
- }
- }
- }
- }
- int main()
- {
- ifstream cin("acm.txt");
- int N,adjNum,tem;
- cin>>N;
- for(int i=0;i<N;i++)
- {
- cin>>adjNum;
- priorityQueue.push_back(i+1);
- Graphic[i][0]=i+1;
- for(int k=1;k<=adjNum;k++)
- {
- cin>>tem;
- Graphic[i][k]=tem;
- }
- }
- for(int i=0;i<N;i++)
- for(int k=0;k<N;k++)
- cin>>Edge[i][k];
- MstPrim(1,N);
- for(int i=0;i<N;i++)
- cout<<key[i]<<endl;
- }