对象:有权无向图(带权连通图)
图的存储:邻接矩阵且有0和INF的那种 or 邻接表。
矩阵实现:
#include<iostream> using namespace std; const int maxn=100; class graph { struct gra { int n;//vertex的个数 int edges[maxn][maxn]; }; gra g; int lowcost[maxn]; int path[maxn]; int total_value;//总代价 const int inf=327627; public : void make_graph() { total_value=0; cin>>g.n;//input vertex number for(int i=0;i<g.n;i++) for(int j=0;j<g.n;j++) { int temp; cin>>temp; if(!temp&&i!=j) g.edges[i][j]=inf; else g.edges[i][j]=temp; } } void prim(int v)//v is begin vertex { for(int i=0;i<g.n;i++) lowcost[i]=g.edges[v][i]; path[0]=v;//起始点 begin vertex for(int i=1;i<g.n;i++) { int minn=inf; int k; for(int j=0;j<g.n;j++) { if(lowcost[j]&&lowcost[j]<minn) { minn=lowcost[j]; k=j; } } path[i]=k;//next vertex total_value+=minn; lowcost[k]=0;//have visited for(int j=0;j<g.n;j++)//用k行去更新lowcost if(lowcost[j]&&g.edges[k][j]<lowcost[j]) lowcost[j]=g.edges[k][j]; } } int disp_total_value() { cout<<total_value<<endl;; } }; int main() { graph g; g.make_graph(); g.prim(0); g.disp_total_value(); return 0; }
邻接表实现:
#include<iostream> using namespace std; const int maxn=100; const int inf=327627; class graph { struct arcnode//vertex { int adjvex; arcnode *nextarc; int weight; }; struct vnode//edges { arcnode *firstarc; }; struct adjgraph { vnode adjlist[maxn]; int n;//vertex number }; adjgraph g; int lowcost[maxn],path[maxn]; int total_value; public : void make_adjgraph() { cin>>g.n; total_value=0; for(int i=0;i<g.n;i++) g.adjlist[i].firstarc=NULL; for(int i=0;i<g.n;i++) for(int j=0;j<g.n;j++) { arcnode *temp=new arcnode; temp->adjvex=j; cin>>temp->weight; if(temp->weight!=0) { temp->nextarc=g.adjlist[i].firstarc; g.adjlist[i].firstarc=temp; } } } void prim(int v) { for(int i=0;i<g.n;i++) lowcost[i]=inf; lowcost[v]=0; path[0]=v; arcnode *p=g.adjlist[v].firstarc; while(p!=NULL) { lowcost[p->adjvex]=p->weight; p=p->nextarc; } for(int i=1;i<g.n;i++) { int minn=inf; int k; for(int j=0;j<g.n;j++) if(lowcost[j]&&lowcost[j]<minn) { minn=lowcost[j]; k=j; } lowcost[k]=0; path[i]=k; total_value+=minn; arcnode *p=g.adjlist[k].firstarc; while(p!=NULL) { if(lowcost[p->adjvex]&&p->weight<lowcost[p->adjvex])//lowcost 表示未拜访 lowcost[p->adjvex]=p->weight; p=p->nextarc; } } } void disp_total_value() { cout<<total_value<<endl; } } ; int main() { graph g; g.make_adjgraph(); g.prim(1); g.disp_total_value(); return 0; }
例题地址:http://120.77.243.165/status.php?user_id=201703120136
HNIEOJ 3960