#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <string.h>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <list>
#include <bitset>
#include <stack>
#include <stdlib.h>
using namespace std;
#define MAXSIZE 20
int indegree[MAXSIZE],outdegree[MAXSIZE];//
typedef char InfoType;//邻接表存储结构类型
typedef char VertexType;//节点数据类型
typedef struct Arcnode//表结点
{
int adjvex;//存放结点的下表
Arcnode *nextarc;//指向下一条弧的指针域
InfoType *info;//该弧相关信息的指针
}Arcnode;
typedef struct VNode//头结点
{
VertexType data;
Arcnode *firstarc;
}VNode,AdjList[MAXSIZE];
typedef struct
{
AdjList vertices;
int vexnum;//顶点数
int arcnum;//边数
int kind;//0为无向图,1为有向图
}ALGraph;
int visited[MAXSIZE];//辅助数组,标志是否访问过
void Create_Graph(ALGraph &G)//
{
char ch1,ch2;
int k1,k2;
cout<<"输入顶点数和边数"<<endl;
cin>>G.vexnum>>G.arcnum;//
cout<<"输入图的顶点"<<endl;
for(int i=1;i<=G.vexnum;i++)
{
getchar();
cin>>G.vertices[i].data;
G.vertices[i].firstarc = NULL;
}
cout<<"请输入边"<<endl;
for(int i=1;i<=G.arcnum;i++)
{
getchar();
cin>>ch1>>ch2;
for(int j = 1;j<=G.arcnum;j++)
if(G.vertices[j].data == ch1)
{
k1 = j;
break;
}
for(int j=1;j<=G.arcnum;j++)
if(G.vertices[j].data == ch2)
{
k2 = j;
break;
}
Arcnode *p;//把新申请的表结点前插
p = new Arcnode();
p->adjvex = k2;
p->nextarc = G.vertices[k1].firstarc;
G.vertices[k1].firstarc = p;
}
}
void Output_Graph(ALGraph G)
{
for(int i=1;i<=G.vexnum;i++)
{
cout<<G.vertices[i].data<<' ';
Arcnode *p;
p = G.vertices[i].firstarc;
while(p)
{
cout<<G.vertices[p->adjvex].data<<' ';
p = p->nextarc;
}
cout<<endl;
}
}
int Topological_Sort(ALGraph G)
{
int s[MAXSIZE]; //stack
int top = 0;
for(int i=1;i<=G.vexnum;i++)
{
if(indegree[i] == 0)
{
top++;
s[top] = i;
}
}
int ans = 0;
int i = 1;
Arcnode *p = NULL;
while(top)
{
i = s[top--];
cout<<i<<' '<<G.vertices[i].data<<endl;
ans++;
for(p=G.vertices[i].firstarc;p;p=p->nextarc)
{
int k = p->adjvex;
indegree[k]--;
if(!indegree[k])
{
s[++top] = k;
}
}
}
if(ans < G.vexnum)
return -1;
return 1;
}
int main()
{
/*
4 4
A B C D
A B
A D
B C
D B
*/
/*
8 9
A B C D E F G H
A H
A B
H B
B C
C D
D E
B G
E F
G F
*/
/*
8 10
A B C D E F G H
H A
B A
H B
C B
C D
D E
B G
E F
G F
E A
*/
cout<<"拓扑排序"<<endl;
ALGraph G;
Create_Graph(G);
cout<<"图的邻接表为:"<<endl;
Output_Graph(G);
int flag = 0;
cout<<"拓扑排序:"<<endl;
flag = Topological_Sort(G);
flag==-1? cout<<"不能进行拓扑排序。"<<endl : cout<<"已经进行拓扑排序。"<<endl;
return 0;
}
拓扑排序
最新推荐文章于 2022-02-22 13:45:59 发布