// // Graph.hpp // lanqiaobei // // Created by 蒋豪博 on 2017/3/14. // Copyright © 2017年 蒋豪博. All rights reserved. // #ifndef Graph_hpp #define Graph_hpp #define NUM 20 #include <string> using namespace std; struct ArcCell{ int adj; }; struct MGraph{ string vexs[NUM]; ArcCell arcs[NUM][NUM]; int vexnum,arcnum; }; struct edge{ int m,n; int weight; }; class Graph{ public: MGraph mgraph; bool CreateUDN(); int locate(string a); void Kruskal(); }; struct mfsNode{ int vex; int parent; }; class MFSet{ public: mfsNode mfs[NUM]; int length=0; void initial(int arr[],int length); int find(int x); int locate(int x); void Union(int x,int y); void insert(int x); void display(); }; #endif /* Graph_hpp */
// // Graph.cpp // lanqiaobei // // Created by 蒋豪博 on 2017/3/14. // Copyright © 2017年 蒋豪博. All rights reserved. // #include <iostream> #include "Graph.hpp" #include <algorithm> #include <vector> using namespace std; #define NONE 1000 bool Graph::CreateUDN(){ cout<<"请输入顶点数:"<<endl; cin>>mgraph.vexnum; cout<<"请输入边数:"<<endl; cin>>mgraph.arcnum; cout<<"请输入端点值:"<<endl; for(int i=0;i<mgraph.vexnum;i++){ cin>>mgraph.vexs[i]; } for(int i=0;i<mgraph.vexnum;i++){ for(int j=0;j<mgraph.vexnum;j++){ mgraph.arcs[i][j].adj=NONE; } } string a,b; int weight; cout<<"请输入边的两个顶点和权值:"<<endl; for(int i=0;i<mgraph.arcnum;i++){ cin>>a>>b>>weight; int m=locate(a); int n=locate(b); mgraph.arcs[m][n].adj=weight; mgraph.arcs[n][m].adj=weight; } return true; } int Graph::locate(string a){ for(int i=0;i<mgraph.vexnum;i++){ if(mgraph.vexs[i]==a){ return i; } } return -1; } void MFSet::initial(int arr[],int length){ this->length=length; for(int i=0;i<length;i++){ mfs[i].vex=i; mfs[i].parent=-1; } } int MFSet::find(int x){ int index=locate(x); int p=mfs[index].parent; while(p!=-1) { index=p; p=mfs[index].parent; } return index; } int MFSet::locate(int x){ for(int i=0;i<length;i++){ if(mfs[i].vex==x){ return i; } } return -1; } void MFSet::Union(int x,int y){ int i=find(x),j=find(y); mfs[j].parent=i; } void MFSet::insert(int x){ mfs[length].vex=x; mfs[length].parent=-1; length++; } void MFSet::display(){ for(int i=0;i<length;i++){ cout<<i<<":"<<mfs[i].vex<<" "<<mfs[i].parent<<endl; } } bool cmp(edge x,edge y){ return x.weight>y.weight; } void Graph::Kruskal(){ vector<edge> arr; for(int i=0;i<mgraph.vexnum;i++){ for(int j=i+1;j<mgraph.vexnum;j++){ if(mgraph.arcs[i][j].adj<NONE){ edge e{i,j,mgraph.arcs[i][j].adj}; arr.push_back(e); } } } MFSet mfset; for(int i=0;i<mgraph.vexnum;i++){ mfset.insert(i); } int count=0; while(count<mgraph.vexnum-1) { make_heap(arr.begin(),arr.end(),cmp); edge e=arr.front(); arr.erase(arr.begin()); int i=mfset.find(e.m); int j=mfset.find(e.n); if(i!=j){ mfset.Union(i,j); cout<<mgraph.vexs[e.m]<<"-"<<mgraph.vexs[e.n]<<"-"<<mgraph.arcs[e.m][e.n].adj<<endl; count++; } } }
#include <iostream> #include <vector> #include <algorithm> #include "Graph.hpp" using namespace std; int main(){ Graph graph; graph.CreateUDN(); graph.Kruskal(); }