《数据结构与算法分析》
//2013/07/01 prim
#include<iostream>
using namespace std;
const int INIT=30000;
typedef int ** Graph;
void InitGraph(Graph &G,int n,int * &visted,int *&D,int *&V)
{
int i;
int j;
G=new int *[n];
for(i=0;i<n;++i)
G[i]=new int [n];
for(i=0;i<n;++i)
for(j=0;j<n;++j)
G[i][j]=INIT;
for(i=0;i<n;++i)
{
visted[i]=0;//访问标志
D[i]=INIT;//与相连节点的距离
V[i]=0;//存放相邻节点
}
}
void CreateGraph(Graph &G,int n,int edge)
{
int i;
int j;
int weight;
int k;
cout<<"Please Create The Graph"<<endl;
for(k=0;k<edge;++k)
{
cin>>i>>j>>weight;
G[i][j]=G[j][i]=weight;
}
}
int mixvertex(Graph &G,int n,int *&D,int *&visted)//查找G中没有被访问且与相邻节点距离最小
{
int i,v;
for(i=0;i<n;++i)
if(!visted[i] ){v=i;break;};
for(i=i+1;i<n;++i)
{
if(!visted[i] && D[i]<D[v])
v=i;
}
return v;
}
void prim(Graph &G,int s,int n,int * &visted,int *&D,int *&V)
{
int i,v,w;
V[0]=s;
for(i=0;i<n;++i)//初始化第一个节点以及更新与其相邻节点的距离
D[i]=G[s][i];
visted[s]=1;
for(i=1;i<n;++i)
{
v=mixvertex(G,n,D,visted);//求出
V[i]=v;
visted[v]=1;
for(w=0;w<n;++w)
{
if(!visted[w]&&D[w]>G[v][w])//更新剩余节点
{
D[w]=G[v][w];
}
}
}
}
void print(int *&V,int n)
{
int i;
for(i=0;i<n;++i)
cout<<V[i]<<endl;
}
int main()
{
int *visted;
int *D;
int *V;
int n=6;
int edge=8;
int i=0;
visted=new int[n];
D=new int [n];
V=new int [n];
Graph G;
InitGraph(G,n,visted,D,V);
CreateGraph(G,n,edge);
prim(G,0,n,visted,D,V);
print(V,n);
}