第六章 6.6 图的应用
6.6.1最小生成树
6.6.2 最短路径
6.6.3 拓扑排序
#include<bits/stdc++.h> #include<stack> using namespace std; #define MVNum 100 #define OK 1 #define ERROR 0 typedef int OtherInfo; typedef int Status; typedef int VerTexType; typedef struct ArcNode{//边结点 int adjvex;//该边所指向的顶点的位置 struct ArcNode *nextarc;//指向下一条边的指针 OtherInfo info;//和边有关的信息 }ArcNode; typedef struct VNode{ VerTexType data;//顶点信息 ArcNode *firstarc;//指向第一条依附该顶点边的指针 }VNode,Adjlist[MVNum];//Adjlist表示邻接表类型 typedef struct{//邻接表 Adjlist vertices; int vexnum,arcnum;//图的当前顶点数和边数 }ALGraph; Status LocateVex(ALGraph G,char ch) { int i; for(i = 0; i < G.vexnum ; i ++) { if(G.vertices[i].data == ch -'0') return i; } } Status CreatUDG(ALGraph &G) { char v1,v2; int i,j,k; ArcNode *p1,*p2; cin>>G.arcnum>>G.vexnum ;//读入图的总边数和顶点数 for(i = 0; i < G.vexnum ; i ++) { cin>>G.vertices[i].data ; G.vertices[i].firstarc = NULL; } for(k = 0; k < G.vexnum ; k ++) { cin>>v1>>v2; i = LocateVex(G,v1); j = LocateVex(G,v2); p1 = new ArcNode; p1->adjvex = j; p1->info = i; p1->nextarc = G.vertices[i].firstarc ; G.vertices[i].firstarc = p1; p2 = new ArcNode; p2->adjvex = i; p2->info = j; p2->nextarc = G.vertices[j].firstarc ; G.vertices[j].firstarc = p2; } return OK; } int FindInDegree(ALGraph G,int indegree[]) { for(int i = 0;i < G.vexnum ;i ++) { ArcNode *p1 = G.vertices[i].firstarc; while(p1->nextarc !=NULL) { indegree[p1->nextarc->adjvex]++; p1 = p1->nextarc ; } } return OK; } Status TopologicalSort(ALGraph G,int topo[]) { stack<int>S; int indegree[MVNum]; int i,m,k; ArcNode *p; memset(indegree,0,sizeof(indegree)); FindInDegree(G,indegree);//求出各顶点的入度存入数组indegree中 for(i = 0; i < G.vexnum ; i ++) { if(!indegree[i])//入度为0者进栈 S.push(i); } m = 0; while(!S.empty()) { i = S.top();//将栈顶vi出栈 S.pop(); topo[m++] = i;//对输出顶点计数 //将vi保存在拓扑排序数组topo中 p = G.vertices[i].firstarc ;//p指向vi的第一个邻接点 while(p != NULL) { k = p->adjvex ;//vk为vi的邻接点 -- indegree[k];//vi的每个邻接点的入度减1 if(indegree[k] == 0)//若入度减为0,则入度 S.push(k); p = p->nextarc ;//p指向顶点vi的下一个邻接点 } } if(m < G.vexnum )//该图有回路 return ERROR; return OK; } int main() { ALGraph G; int topo[MVNum]; CreatUDG(G); TopologicalSort(G,topo); return 0; }