-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path拓扑排序
167 lines (131 loc) · 2.93 KB
/
拓扑排序
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//
// main.c
// toposort
//
// Created by 毛遵杰 on 2019/12/13.
// Copyright © 2019 毛遵杰. All rights reserved.
//
#include <stdio.h>
#define MAX 100
typedef char VertexType;
typedef struct ArcNode {
int adjvex;
struct ArcNode *next;
int weight;
}ArcNode;
typedef struct VertexNode {
VertexType data;
ArcNode *firstArc;
}VertexNode,AdjVerList[MAX];
typedef struct {
AdjVerList vertices;
int vexnum,arcnum;
}ALGraph;
int indegree[MAX];
void CreateALGraph(ALGraph *G);
void Display(ALGraph *G);
int TopoSort(ALGraph *G);
int main()
{
ALGraph G;
CreateALGraph(&G);
//Display(&G);
TopoSort(&G);
return 0;
}
//vertex position
int LocateVex(ALGraph *G,VertexType v)
{
int i;
for(i=0;i<G->vexnum;i++)
{
if(G->vertices[i].data == v)
return i;
}
return -1;
}
void CreateALGraph(ALGraph *G)
{
VertexType v1,v2;
int w;
ArcNode *Arc;
printf("please enter the vertex and arc");
cin>>G->vexnum>>G->arcnum;
printf("please enter data of vertex:");
for(int i=0;i<G->vexnum;i++){
cin>>G->vertices[i].data;
G->vertices[i].firstArc = NULL;
}
printf("enter %d The two vertices corresponding to the group edges and their weights, separated by spaces:\n",G->arcnum);
for(int k=0;k<G->arcnum;k++) {
cin>>v1>>v2>>w;
int i = LocateVex(G,v1);
int j = LocateVex(G,v2);
Arc = new ArcNode;
Arc->adjvex = j;
Arc->weight = w;
Arc->next = G->vertices[i].firstArc;
G->vertices[i].firstArc = Arc;
}
}
void Display(ALGraph *G)
{
ArcNode *p;
printf("numbering, vertex, Vertices of adjacent edges\n");
for(int i=0;i<G->vexnum;i++)
{
printf("%d,%d,%d",i,t,G->vertices[i].data);
for(p=G->vertices[i].firstArc;p!=NULL;p=p->next)
printf("t",p->adjvex);
printf("\n");
}
}
void FindIndegree(ALGraph *G)
{
int i;
ArcNode *p;
for(i=0;i<G->vexnum;i++)
indegree[i] = 0;
for(i=0;i<G->vexnum;i++)
{
p = G->vertices[i].firstArc;
while(p)
{
indegree[p->adjvex]++;
p = p->next;
}
}
}
int TopoSort(ALGraph *G)
{
printf("A topological sorting result of the directed graph is:");
stack<int> s;
ArcNode *p;
int i,k;
FindIndegree(G);
for(i=0;i<G->vexnum;i++)
{
if(indegree[i]==0)
s.push(i);
}
int count = 0;
while(!s.empty())
{
i = s.top();
s.pop();
printf("%d",G->vertices[i].data);
count++;
p = G->vertices[i].firstArc;
while(p!=NULL)
{
k = p->adjvex;
indegree[k]--;
if(indegree[k]==0)
s.push(k);
p = p->next;
}
}
if(count<G->vexnum)
return -1;
else
return 0;