forked from Vencenter/C_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
图_拓扑排序_判断图是否有环_.cpp
145 lines (137 loc) · 2.74 KB
/
图_拓扑排序_判断图是否有环_.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include<stdio.h>
#include<stdlib.h>
#include<stack>
#define ElenType int
#define Max 20
using namespace std;
typedef struct ArcNode
{
int adjvex;
struct ArcNode *next;
int info;//weight
}ArcNode;
typedef struct VexNode
{
int data;
struct ArcNode *first;
}VexNode,AdjList[20];//1,2,3,4,5
typedef struct
{
AdjList vertices;
int vernum,arcvem;
}Graph;
int indegree[Max];
int createAdj(Graph &p)
{
printf("请输入顶点个数,边的个数:\n");
scanf("%d%d",&p.vernum,&p.arcvem);
//printf("%d,%d",p.vernum,p.arcvem);
printf("请输入顶点信息,1,2,3...:\n");
for(int i = 0; i < 20; i++)
{
p.vertices[i].first = NULL;
}
for(int i=0;i<p.vernum;i++)
{
scanf("%d",&p.vertices[i].data);
p.vertices[i].first=NULL;
}
printf("请输入有向图相连的边:\n");
int l,r,w;
ArcNode *T;
for(int j=0;j<p.arcvem;j++)
{
//scanf("%d%d%d",&l,&r,&w);
scanf("%d%d",&l,&r);
T=(ArcNode*)malloc(sizeof(ArcNode));
T->adjvex=r;
T->info=w;
T->next=p.vertices[l].first;
p.vertices[l].first=T;
}
}
void PrintfGraph(Graph G)
{
for(int i = 0; i < G.vernum; i++)
{
int index=G.vertices[i].data;
ArcNode *p = G.vertices[index].first;
printf("%d->",G.vertices[i].data);
while(p)
{
printf("%d->",p->adjvex);
p = p->next;
}
printf("NULL\n");
}
}
void FindInDegree( Graph g, int indegree[])
{ //求每个顶点的入度
int i;
ArcNode *p;
for (i=0;i<g.vernum;i++)
{
int index=g.vertices[i].data;
indegree[index]=0;
}
for (i=0;i<g.vernum;i++)
{
int index=g.vertices[i].data;
p=g.vertices[index].first;
while(p)
{
indegree[p->adjvex]++;
p=p->next;
}
}
}
void TopuSort(Graph g)
{
int count;
int k,i;
ArcNode *p;
stack<int>s;
FindInDegree(g,indegree) ; //对各顶点求入度
for(i=0;i<g.vernum;i++ ) //将入度为0的顶点压入栈
{
int index=g.vertices[i].data;
if(!indegree[index])
{
s.push(index);
}
}
count=0;
printf ("\n");
while(!s.empty())
{
i=s.top();
s.pop();
printf ("%d \n",i); //输出拓扑排序序列
count++;
for(p=g.vertices[i].first;p;p=p->next)
{
k=p->adjvex;
//printf ("+%d \n",k);
if (!(--indegree[k]))
{
s.push(k);
}
}
}
if(count<g.vernum)
{
printf("\n该图有回路\n");
}
else
{
printf ("\n该图无回路\n");
}
}
int main()
{
Graph p;
createAdj(p);
PrintfGraph(p);
TopuSort(p);
return 0;
}