安排教学计划
学校每学期开设的课程是有先后顺序的,如计算机专业:开设《数据结构》课程之前,必须先开设《C语言程序设计》和《离散数学》课程,这种课程开设的先后顺序称为先行、后继课程关系。现在需要根据给定的课程信息及课程之间的先行、后继关系,合理安排出开设各门课程的先后顺序。
设计要求
- 对输入的课程先行、后继关系如果存在回路关系时应提示错误
- 根据读入的课程信息及其先行、后继关系,计算出安排教学计划的序列
- 输出教学计划的安排顺序或给出错误提示信息
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
| #include <stdio.h> #include <stdlib.h> #define MAX_COURSES 100
typedef struct Course { int id; char name[50]; int prereq_count; int prereq[MAX_COURSES]; int visited; } Course; Course courses[MAX_COURSES]; int courses_count = 0;
void addCourse(char* name, int prereq_count, int prereq[]) { Course new_course; new_course.id = courses_count; strcpy(new_course.name, name); new_course.prereq_count = prereq_count; for (int i = 0; i < prereq_count; i++) { new_course.prereq[i] = prereq[i]; } new_course.visited = 0; courses[courses_count++] = new_course; }
int hasCycle(int course_id) { if (courses[course_id].visited == 1) { return 1; } if (courses[course_id].visited == 2) { return 0; } courses[course_id].visited = 1; for (int i = 0; i < courses[course_id].prereq_count; i++) { if (hasCycle(courses[course_id].prereq[i])) { return 1; } } courses[course_id].visited = 2; return 0; }
void topologicalSort() { int indegree[MAX_COURSES] = { 0 }; for (int i = 0; i < courses_count; i++) { for (int j = 0; j < courses[i].prereq_count; j++) { indegree[courses[i].prereq[j]]++; } } printf("教学计划:\n"); for (int i = 0; i < courses_count; i++) { int j; for (j = 0; j < courses_count; j++) { if (indegree[j] == 0) { printf("%s\n", courses[j].name); indegree[j] = -1; for (int k = 0; k < courses[j].prereq_count; k++) { indegree[courses[j].prereq[k]]--; } break; } } if (j == courses_count) { printf("错误:在课程先决条件中检测到循环。\n"); return; } } } int main() { addCourse("C语言程序设计", 0, NULL); addCourse("离散数学", 0, NULL); addCourse("数据结构", 2, (int[]) { 0, 1 }); for (int i = 0; i < courses_count; i++) { if (hasCycle(i)) { printf("错误:在课程先决条件中检测到循环。\n"); return 0; } } topologicalSort(); return 0; }
|