#include <stdio.h>
#include <stdlib.h>
#include <string.h>//我这里的头以及尾巴与书上的不一样。
typedef struct ArcNode
{
int from, to;
struct ArcNode * fnext, *tonext;
int w;
}ArcNode;
typedef struct VertexNode
{
char info;
ArcNode *ff, *ft;
}VertexNode;
typedef struct Graph
{
int num_vertex;
int num_arc;
VertexNode *ver;
}Graph;
Graph *Create(int n)
{
Graph * G = (Graph*)malloc(sizeof(Graph));
G->num_vertex = n;
G->num_arc = 0;
G->ver = (VertexNode*)calloc(n+1, sizeof(VertexNode));
for(int i = 1; i <= n; i++)
{
G->ver[i].ff = NULL;
G->ver[i].ft = NULL;//在这里可以补加点的信息
}
return G;
}
void AddArc(Graph *G,int a, int b, int c)
{
(G->num_arc)++;
ArcNode *s = (ArcNode*)malloc(sizeof(ArcNode));
s->from = a;
s->to = b;
s->fnext = G->ver[a].ff;
G->ver[a].ff = s;
s->tonext = G->ver[b].ft;
G->ver[b].ft = s;
s->w = c;
}
//手写一个栈
typedef struct stack{
int *data;
int cnt;
int max;
}Stack;
Stack *Create_Stack(int max)
{
Stack *s = (Stack*)malloc(sizeof(Stack));
s->cnt = -1;
s->data = (int *)calloc(max, sizeof(int));
s->max = max;
return s;
}
void Pop_Stack(Stack *S)
{
if(S->cnt > -1)
S->cnt--;
}
void Push_Stack(Stack *S, int e)
{
if(S->cnt < S->max)
{
S->cnt++;
S->data[S->cnt] = e;
}
}
int Top_Stack(Stack *S)
{
if(S->cnt > -1)
{
return S->data[S->cnt];
}
return 0x3f3f3f3f;
}
void Destory_Stack(Stack *S)
{
free(S->data);
free(S);
}
int Empty_Stack(Stack *S)
{
if(S->cnt == -1)
return 1;
return 0;
}
//进行topo排序
void TopoSort(Graph *G)
{
int total = 0;
Stack* s = Create_Stack(G->num_vertex+2);
int *in = (int *)calloc(G->num_vertex+1,sizeof(G));
for(int i = 1; i <= G->num_vertex; i++)
{
int cnt = 0;
for(ArcNode *A = G->ver[i].ft; A; A = A->tonext)
cnt++;
in[i] = cnt;
if(cnt == 0)
Push_Stack(s, i);
}
while(!Empty_Stack(s))
{
int t = Top_Stack(s);
printf("%d ",t);
total ++;
Pop_Stack(s);
for(ArcNode *A = G->ver[t].ff; A; A = A->fnext)
{
in[A->to]--;
if(in[A->to]==0)
Push_Stack(s, A->to);
}
}
Destory_Stack(s);
if(total != G->num_vertex)
printf("有环!!!");
}
int main()
{
int n,m;
scanf("%d",&n);
Graph *G = Create(n);
scanf("%d",&m);
for(int i = 1; i <= m; i++)
{
int a, b;
scanf("%d%d",&a, &b);
AddArc(G,a,b,0);
}
TopoSort(G);
return 0;
}
/*测试一
9 11
1 3
1 8
8 9
3 4
9 7
4 7
2 3
2 4
2 5
5 6
4 6
*/
04-03
2917
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)