Prim
#include<bits/stdc++.h>
using namespace std;
const int MaxVertexNum=100;
map<char,int> NodeIndex;
bool visited[MaxVertexNum];
typedef struct{
char Vex[MaxVertexNum];
int Edge[MaxVertexNum][MaxVertexNum];
int vexnum,arcnum;
}MGraph;
int Prim(MGraph G,char x){
vector<int> flag(G.vexnum,0);
vector<int> dis(G.vexnum,0);
for(int i=0;i<G.vexnum;i++)
dis[i]=G.Edge[NodeIndex[x]][i];
flag[NodeIndex[x]]=1;
cout<<x<<" ";
int sumDis=0;
for(int i=1;i<G.vexnum;i++){
int minDis=INT_MAX,k;
for(int j=0;j<G.vexnum;j++){
if(flag[j]==0 && minDis>dis[j]){
minDis=dis[j];
k=j;
}
}
flag[k]=1;
cout<<G.Vex[k]<<" ";
sumDis+=minDis;
for(int j=0;j<G.vexnum;j++){
if(flag[j]==0 && dis[j]>G.Edge[k][j])
dis[j]=G.Edge[k][j];
}
}
cout<<endl;
return sumDis;
}
int main(){
MGraph G;
cout<<"请输入结点总数与边数"<<endl;
cin>>G.vexnum>>G.arcnum;
char vnode;
cout<<"请输入结点名称"<<endl;
for(int i=0;i<G.vexnum;i++){
cin>>vnode;
G.Vex[i]=vnode;
NodeIndex[vnode]=i;
}
for(int i=0;i<G.vexnum;i++){
for(int j=i+1;j<G.vexnum;j++){
G.Edge[i][j]=INT_MAX;
G.Edge[j][i]=INT_MAX;
}
G.Edge[i][i]=0;
}
char vex1,vex2;
int weight;
cout<<"请输入相连的结点以及边权值"<<endl;
for(int i=0;i<G.arcnum;i++){
cin>>vex1>>vex2>>weight;
G.Edge[NodeIndex[vex1]][NodeIndex[vex2]]=weight;
G.Edge[NodeIndex[vex2]][NodeIndex[vex1]]=weight;
}
cout<<"请输入最小生成树的根节点"<<endl;
char x;
cin>>x;
cout<<Prim(G,x)<<endl;
return 0;
}
Kruskal
#include<bits/stdc++.h>
using namespace std;
const int MaxVertexNum=100;
map<char,int> NodeIndex;
vector<int> root;
typedef struct{
char Vex[MaxVertexNum];
int Edge[MaxVertexNum][MaxVertexNum];
int vexnum,arcnum;
}MGraph;
typedef struct{
int u,v;
int w;
}Edge;
int findroot(int k){
if(root[k]==k)
return k;
else
root[k]=findroot(root[k]);
return root[k];
}
bool cmp(Edge a,Edge b){
return a.w<b.w;
}
int Kruskal(MGraph G){
int dis=0;
for(int i=0;i<G.vexnum;i++)
root.push_back(i);
vector<Edge> edge;
for(int i=0;i<G.vexnum;i++){
for(int j=i+1;j<G.vexnum;j++){
Edge tmp;
tmp.u=i;
tmp.v=j;
tmp.w=G.Edge[i][j];
edge.push_back(tmp);
}
}
sort(edge.begin(),edge.end(),cmp);
int edge_num=0;
for(int i=0;i<G.arcnum;i++){
int u_root=findroot(edge[i].u);
int v_root=findroot(edge[i].v);
if(u_root!=v_root){
edge_num++;
cout<<edge_num<<":"<<G.Vex[edge[i].u]<<"--"<<G.Vex[edge[i].v]<<endl;
dis+=edge[i].w;
root[u_root]=v_root;
}
if(edge_num==G.vexnum-1)
break;
}
return dis;
}
int main(){
MGraph G;
cout<<"请输入结点总数与边数"<<endl;
cin>>G.vexnum>>G.arcnum;
char vnode;
cout<<"请输入结点名称"<<endl;
for(int i=0;i<G.vexnum;i++){
cin>>vnode;
G.Vex[i]=vnode;
NodeIndex[vnode]=i;
}
for(int i=0;i<G.vexnum;i++){
for(int j=i+1;j<G.vexnum;j++){
G.Edge[i][j]=INT_MAX;
G.Edge[j][i]=INT_MAX;
}
G.Edge[i][i]=0;
}
char vex1,vex2;
int weight;
cout<<"请输入相连的结点以及边权值"<<endl;
for(int i=0;i<G.arcnum;i++){
cin>>vex1>>vex2>>weight;
G.Edge[NodeIndex[vex1]][NodeIndex[vex2]]=weight;
G.Edge[NodeIndex[vex2]][NodeIndex[vex1]]=weight;
}
cout<<Kruskal(G)<<endl;
return 0;
}