拓扑排序(判断有向图是否有回路)
来源:互联网 发布:淘宝花卉 编辑:程序博客网 时间:2024/06/05 21:06
- #include <iostream>
- #include <queue>
- #include <string>
- using namespace std;
-
-
- typedef struct ArcNode{
- int adjvex;
- ArcNode *nextarc;
- }ArcNode;
-
-
- typedef struct VNode{
- string data;
- ArcNode *firstarc;
- }VNode, AdjList[10];
-
- typedef struct ALGraph{
- AdjList vertices;
- int vexnum, arcnum;
- }ALGraph;
-
- int LocateVex(ALGraph G, string u)
- {
- for(int i=0; i<G.vexnum; i++)
- if(G.vertices[i].data==u)
- return i;
- return -1;
- }
-
- void CreateDG(ALGraph &G)
- {
- string v1, v2;
- int i, j, k;
- cout<<"请输入顶点数和边数:";
- cin>>G.vexnum>>G.arcnum;
-
- cout<<"请输入顶点:";
- for(i=0; i<G.vexnum; i++)
- {
- cin>>G.vertices[i].data;
- G.vertices[i].firstarc=NULL;
- }
-
- cout<<"请输入边:"<<endl;
- for(k=0; k<G.arcnum; k++)
- {
- cin>>v1>>v2;
- i=LocateVex(G, v1);
- j=LocateVex(G, v2);
-
- ArcNode* arc=new ArcNode;
- arc->adjvex=j;
- arc->nextarc=G.vertices[i].firstarc;
- G.vertices[i].firstarc=arc;
- }
- }
-
- void FindIndegree(ALGraph G, int indegree[])
- {
- for(int i=0; i<G.vexnum; i++)
- indegree[i]=0;
-
- for(i=0; i<G.vexnum; i++)
- {
- ArcNode *p=G.vertices[i].firstarc;
- while(p)
- {
- indegree[p->adjvex]++;
- p=p->nextarc;
- }
- }
- }
-
- void TopologicalSort(ALGraph G)
- {
- queue<int> q;
- int indegree[10]={0};
- int count=0;
-
- FindIndegree(G, indegree);
-
- for(int i=0; i<G.vexnum; i++)
- if(0==indegree[i])
- q.push(i);
-
- while(!q.empty())
- {
- int v=q.front();
- q.pop();
- count++;
- cout<<G.vertices[v].data<<" ";
- ArcNode *p=G.vertices[v].firstarc;
- while(p)
- {
- if(!(--indegree[p->adjvex]))
- q.push(p->adjvex);
- p=p->nextarc;
-
- }
- }
-
- if(count<G.vexnum)
- cout<<"该有向图有回路"<<endl;
- }
-
- void main()
- {
- ALGraph G;
- CreateDG(G);
-
- cout<<"拓扑排序:";
- TopologicalSort(G);
- cout<<endl;
-
-
-
- }
测试用例一:
测试用例二:
0 0