算法导论用于不相交集合的数据结构
2017-04-08 17:18
246 查看
#include<iostream> #include<string> #include<list> using namespace std; typedef char VertexType; //顶点类型应由用户定义 typedef int EdgeType; //边上的权值类型应由用户定义 #define MAXVEX 100 //最大顶点数,应由用户定义 #define INFINITY 65535 //用65535来代表无穷大 struct Node { bool flag=true; list<char> L; }; Node* node[MAXVEX]; //邻接矩阵结构 typedef struct { VertexType vexs[MAXVEX]; //顶点表 EdgeType arc[MAXVEX][MAXVEX]; //邻接矩阵,可看作边 int numVertexes, numEdges; //图中当前的顶点数和边数 }Graph; //定位 int locates(Graph *g, char ch) { int i; for (i = 0; i < g->numVertexes; i++) { if (g->vexs[i] == ch) { break; } } if (i >= g->numVertexes) { return -1; } return i; } //建立一个无向网图的邻接矩阵表示 void CreateGraph(Graph *g) { int i, j, k, w; cout<<"输入顶点数和边数:"; cin >> g->numVertexes >> g->numEdges; cout << "请输入顶点:"<<endl; for (i = 0; i < g->numVertexes; i++) { cin >> g->vexs[i]; } for (i = 0; i < g->numVertexes; i++) { for (j = 0; j < g->numVertexes; j++) { g->arc[i][j] = INFINITY; //邻接矩阵初始化 } } for (k = 0; k < g->numEdges; k++) { char p, q; cout << "输入边(vi,vj):" << endl; cin >> p >> q; int m = -1; int n = -1; m = locates(g, p); n = locates(g, q); if (n == -1 || m == -1) { fprintf(stderr, "there is no this vertex.\n"); return; } g->arc[m] = 1; g->arc [m] = g->arc[m] ; //因为是无向图,矩阵对称 } } int FIND_SET(Graph *g,char u) { int count; for(int i=0;i<g->numVertexes;i++) { list<char>::iterator it; if(node[i]->flag==true) { for(it = node[i]->L.begin();it!=node[i]->L.end();it++){ if(*it==u) { count=i; } } } } return count; } void CONNECTED_COMPONENTS(Graph *g) { int i,j; for(i=0;i<g->numVertexes;i++) { node[i]=new Node; node[i]->L.push_back(g->vexs[i]); } for(i=0;i<g->numVertexes;i++) { for(j=i+1;j<g->numVertexes;j++){ if(g->arc[i][j]==1){ int m=FIND_SET(g,g->vexs[i]); int n=FIND_SET(g,g->vexs[j]); if(m!=n) { node[m]->L.merge(node ->L); node ->flag=false; } } } } } void Print(Graph *g) { cout<<"该无向图的连通分量为:"<<endl; for(int i=0;i<g->numVertexes;i++){ if(node[i]->flag==true) { list<char>::iterator it; cout<<"{"; for(it = node[i]->L.begin();it!=node[i]->L.end();it++){ cout<<*it<<","<<" "; } cout<<"\b"<<"\b"<<"}"; cout<<endl; } } } int main(){ Graph g; //邻接矩阵创建图 CreateGraph(&g); CONNECTED_COMPONENTS(&g); Print(&g); return 0; }
相关文章推荐
- 算法导论 第二十一章 用于不相交集合的数据结构
- 算法导论代码 第21章 用于不相交集合的数据结构
- 算法导论之用于不相交集合的数据结构
- 算法导论学习笔记-第二十一章-用于不相交集合的数据结构
- 算法导论 第21章 用于不相交集合的数据结构
- 算法导论习题解-第21章用于不相交集合的数据结构
- 算法导论21(用于不相交集合的数据结构)
- 算法导论 第21章 用于不相交集合的数据结构
- 算法导论——用于不相交集合的数据结构
- 算法导论笔记:21用于不相交集合的数据结构
- 算法导论学习笔记(15)——用于不相交集合的数据结构
- [算法导论读书笔记]用于不相交集合的数据结构(并查集)
- 算法导论-用于不想交集合的数据结构(并查集)-kruskal最小生成树算法
- 用于不相交集合的数据结构(并查集)
- 算法导论-用于不相交集合的数据结构
- 算法导论-用于不想交集合的数据结构(并查集)-kruskal最小生成树算法
- 用于不相交集合的数据结构——查并集
- 用于不相交集合的数据结构——查并集
- 用于不相交集合的数据结构
- 第21章:用于不相交集合的数据结构