总结下算法好了:
(1)构图:每个活动是一个顶点,如果A必须排在B前面,那么有边从顶点A指向顶点B,顶点B的入度+1
(2)遍历所有顶点,将入度为0的顶点入栈
(3)如果栈不为空,则将栈顶出栈,然后将该顶点从图中删掉,即该点指向的点的入度-1,如果减后为0则入栈,重复(3)
简单版的代码,只能举出一种拓扑排序:
1 #include <stdio.h> 2 #include <string.h> 3 4 #define MAX_VERTEX_NUM 100 5 6 int ver_num; 7 char vertex[MAX_VERTEX_NUM]; 8 int indeg[MAX_VERTEX_NUM]; 9 int graph[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; 10 11 void CreateMGragh() 12 { 13 int i,j; 14 int n1,n2,f1,f2; 15 char ch1,ch2,ch3; 16 while(1){ 17 scanf("%c%c%c",&ch1,&ch2,&ch3); 18 f1 = f2 = 0; 19 for (i=0; vertex[i] != 0; i++){ 20 if (vertex[i] == ch1){ 21 f1 = 1; 22 n1 = i; 23 break; 24 } 25 } 26 if (f1 == 0){ 27 vertex[i] = ch1; 28 n1 = i; 29 } 30 for (j=0; vertex[j] != 0; j++){ 31 if (vertex[j] == ch2){ 32 f2 = 1; 33 n2 = j; 34 break; 35 } 36 } 37 if (f2 == 0){ 38 vertex[j] = ch2; 39 n2 = j; 40 } 41 42 graph[n1][n2] = 1; 43 indeg[n2]++; 44 45 46 if (ch3 == '\n'){ 47 break; 48 } 49 } 50 for (i=0; vertex[i] != 0; i++); 51 ver_num = i; 52 } 53 54 void topsort() 55 { 56 int stack[MAX_VERTEX_NUM]; 57 int i,top; 58 59 top = 0; 60 memset(stack,0,sizeof(stack)); 61 62 // 入度为0的点都入栈 63 for (i=0; i<ver_num; i++){ 64 if (indeg[i] == 0){ 65 stack[top++] = i; 66 } 67 } 68 69 while(0 != top){ 70 // 出栈 71 printf("%c",vertex[stack[--top]]); 72 73 // 把这个点删掉 即它后面的点的入度-1 并把连线去掉 74 for (i=0; i<ver_num; i++){ 75 if (graph[stack[top]][i] == 1){ 76 graph[stack[top]][i] = 0; 77 indeg[i]--; 78 if (indeg[i] == 0){ 79 stack[top++] = i; 80 } 81 } 82 } 83 } 84 printf("\n"); 85 } 86 87 int main() 88 { 89 CreateMGragh(); 90 topsort(); 91 return 0; 92 }
测试用例及结果:
来源:https://www.cnblogs.com/raul-ac/p/3271501.html