//Note: Chinese Character can not be displayed in Win98
#include<iostream>
#include<string>
#define MAX_VEX_NUM 20
const int MAX = 30;
using namespace std;
typedef int SElemtype;
typedef struct ArcNode{
int adjvex;
ArcNode *nextarc;
}ArcNode;
typedef struct VNode
{
string data;
ArcNode *firstarc;
}Adjlist[MAX_VEX_NUM];
typedef struct Graph
{
int vexnum;
int arcnum;
Adjlist vertices;
int degree[MAX_VEX_NUM];
}Graph;
typedef struct {
SElemtype *base;
SElemtype *top;
int size;
}SqStack;
bool InitStack(SqStack &s)
{
s.size = MAX;
s.base = new SElemtype[MAX];
s.top = s.base;
return true;
}
bool GetTop(SqStack s,SElemtype &e)
{
if(s.top == s.base)
return false;
--s.top;
e = *s.top;
return true;
}
bool IsStackEmpty(SqStack &s)
{
if(s.top == s.base)
return true;
else
return false;
}
bool Push(SqStack &s,SElemtype e)
{
if(s.top - s.base >= MAX)
return false;
*s.top = e;
++s.top;
return true;
}
bool Pop(SqStack &s,SElemtype &e)
{
if(s.top == s.base )
return false;
--s.top;
e = *s.top;
return true;
}
int LocateVex(Graph &gf,string data)
{
for(int i = 0 ; i < gf.vexnum; ++i)
if(data == gf.vertices[i].data)
return i ;
return -1;
}
void CreateGraph(Graph &gf)
{
cout<<"please input node number and arc number :"<<endl;
cin>>gf.vexnum;
cin>>gf.arcnum;
cout<<"输入顶点:"<<endl;
for (int i = 0; i< gf.vexnum; ++i)
{
gf.vertices[i].firstarc = NULL;
cin>>gf.vertices[i].data;
}
cout<<"输入各个弧,格式:弧尾,弧头:"<<endl;
int start;
int end;
string data;
for(int i = 0; i < gf.arcnum; ++i)
{
cin>>data;
start = LocateVex(gf,data);
if(start == -1)
return;
cin>>data;
end = LocateVex(gf,data);
if(end == -1)
return ;
ArcNode *node = new ArcNode;
node->adjvex = end;
node->nextarc = gf.vertices[start].firstarc;
gf.vertices[start].firstarc = node;
}
}
void ReleaseGraph(Graph &gf)
{
ArcNode *p;
for(int i = 0; i < gf.vexnum; ++i)
{
for(p = gf.vertices[i].firstarc;p;p = gf.vertices[i].firstarc)
{
gf.vertices[i].firstarc = p->nextarc;
delete p;
}
}
}
void FindInDegree(Graph &gf)
{
ArcNode *p;
for(int i = 0; i < gf.vexnum; ++i)
gf.degree[i] = 0;
for(int i = 0; i < gf.vexnum; ++i)
{
for(p = gf.vertices[i].firstarc;p;p = p->nextarc)
++gf.degree[p->adjvex];
}
}
bool TopLogicalSort(Graph gf)
{
SqStack s;
FindInDegree(gf);
InitStack(s);
for(int i = 0; i < gf.vexnum; ++i)
if(!gf.degree[i]) Push(s,i);
int count = 0;
int i;
ArcNode *p;
while(!IsStackEmpty(s))
{
Pop(s,i);
cout<<i<<" "<<gf.vertices[i].data <<" ";
++count;
for(p = gf.vertices[i].firstarc; p; p = p->nextarc)
{
--gf.degree[p->adjvex];
if(!gf.degree[p->adjvex])Push(s,p->adjvex);
}
}
if(count < gf.vexnum ) return false;
return true;
}
int main()
{
Graph gf;
CreateGraph(gf);
if(!TopLogicalSort(gf)) cout<<"Wrong Graph";
ReleaseGraph(gf);
return 0;
}